Linux如何顯示文件指定行數的內容;顯示第一行、中間幾行和最后幾行


1、tail -n +/-數字 文件名

2、head -n 數字 文件名

3、sed -n "開始行,結束行p" 文件名

4、sed -n '1p;20,40p; "顯示第一行和20到40行'

5、sed -n 7p file_name : 顯式第7行

6、cat file_name | awk 'NR==1 || NR==2 || NR==10'  顯式第1、2、10行

 統計行數的幾種方法:

wc -l  test.txt顯示文件的行數

sed -n '$=' test.txt 顯示文件的行數  -n表示只打印匹配的結果

grep -c "" filename        -c, --count               print only a count of matching lines per FILE

awk 'END{print NR}' filename   awk的BEGIN和END表示匹配開始之前匹配結束之后執行的動作

效率對比:

生成測試所需文件:awk 'BEGIN{for(i=0;i<10000000;i++)print i}'>>test

wc方法: time wc -l test

1、time wc -l test  用時0.026s
1000000 test

real    0m0.014s
user    0m0.009s
sys    0m0.003s

2、grep方法,用時0.080s

time grep -c "" test
1000000

real    0m0.041s
user    0m0.037s
sys    0m0.002s

3、用時0.159s

time sed -n '$=' test
1000000

real    0m0.080s
user    0m0.073s
sys    0m0.006s

4、用時0.095s

time awk 'END{print NR}' test
1000000

real    0m0.049s
user    0m0.042s
sys    0m0.004s

結論:wc>grep>awk>sed

參考:1、http://www.linuxidc.com/Linux/2012-06/63680.htm

2、http://man.linuxde.net/sed

3、http://man.linuxde.net/awk


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM