1. 程式人生 > >How would you print just the 10th line of a file?

How would you print just the 10th line of a file?

How would you print just the 10th line of a file?

For example, assume that file.txt has the following content:

Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
Your script should output the tenth line, which is:
Line 10
[show hint]

Hint:
1. If the file contains less than 10 lines, what should you output?
2. There's at least three different solutions. Try to explore all possibilities.
Subscribe to see which companies asked this question

思路分析:

sed是一個很好的檔案處理工具,本身是一個管道命令,主要是以行為單位進行處理,可以將資料行進行替換、刪除、新增、選取等特定工作,下面先了解一下sed的用法
sed命令列格式為:
         sed [-nefri] ‘command’ 輸入文字        
常用選項:
        -n∶使用安靜(silent)模式。在一般 sed 的用法中,所有來自 STDIN的資料一般都會被列出到螢幕上。但如果加上 -n 引數後,則只有經過sed 特殊處理的那一行(或者動作)才會被列出來。
        -e∶直接在指令列模式上進行 sed 的動作編輯;
        -f∶直接將 sed 的動作寫在一個檔案內, -f filename 則可以執行 filename 內的sed 動作;
        -r∶sed 的動作支援的是延伸型正規表示法的語法。(預設是基礎正規表示法語法)
        -i∶直接修改讀取的檔案內容,而不是由螢幕輸出。       
常用命令:
        a   ∶新增, a 的後面可以接字串,而這些字串會在新的一行出現(目前的下一行)~
        c   ∶取代, c 的後面可以接字串,這些字串可以取代 n1,n2 之間的行!
        d   ∶刪除,因為是刪除啊,所以 d 後面通常不接任何咚咚;
         i   ∶插入, i 的後面可以接字串,而這些字串會在新的一行出現(目前的上一行);
         p  ∶列印,亦即將某個選擇的資料印出。通常 p 會與引數 sed -n 一起運作~
         s  ∶取代,可以直接進行取代的工作哩!通常這個 s 的動作可以搭配正規表示法!例如 1,20s/old/new/g 就是啦!

程式碼:

sed -n '10p' file.txt  
--------------------- 
作者:hellochenlu 
來源:CSDN 
原文:https://blog.csdn.net/hellochenlu/article/details/50893704 
版權宣告:本文為博主原創文章,轉載請附上博文連結!