1. 程式人生 > >linux下檢視檔案第20-30行內容的N種方法及命令介紹

linux下檢視檔案第20-30行內容的N種方法及命令介紹

首先建立檔案及填充內容

[root@VM_179_129_centos tmp]# seq 100 > /tmp/seq.txt

結果展示
這裡寫圖片描述

這裡寫圖片描述

命令介紹:seq 用於產生從某個數到另外一個數之間的所有整數。
seq [選項]… 尾數 (從1到尾數 增量為1)
seq [選項]… 首數 尾數 (從首數到尾數 增量為1)
seq [選項]… 首數 增量 尾數

[root@VM_179_129_centos tmp]# seq 1 3 10 > ett.txt
[root@VM_179_129_centos tmp]# cat ett.txt
1
4
7
10

下面開始進入正題:

方法1: (head 和 tail通過管道組合)

[root@VM_179_129_centos tmp]# head -30 ett.txt | tail -11
20
21
22
23
24
25
26
27
28
29
30

命令解釋:head -n 30 xxx.txt == head -30 xxx.txt 取檔案前30行內容
tail -11 xxx.txt 取檔案後11行內容
| 管道命令連線 將head取出的30行內容作為tail的輸入

方法2: awk命令

[root@VM_179_129_centos tmp]# awk 'NR==20,NR==30' ett.txt 
20 21 22 23 24 25 26 27 28 29 30

awk命令中 NR表示行號,直譯 取20-30行的內容
awk ‘NR==35’ ett.txt 取第35行內容

方法3:sed命令

[root@VM_179_129_centos tmp]# sed -n '20,30p' ett.txt
20
21
22
23
24
25
26
27
28
29
30

sed命令 中-n 引數搭配p 一起來使用
1.列印檔案的第二行
sed -n ‘2p’ file
2.列印1到3行
sed -n ‘1,3p’ file
3.品配單詞用/patten/模式,eg,/Hello/
sed -n ‘/Hello/’p file
4

.使用模式和行號進行品配,在第4行查詢Hello
sed -n ‘4,/Hello/’ file
5.配原字元(顯示原字元$之前,必須使用\遮蔽其特殊含義)
sed -n ‘/$/’p file
上述命令將把file中含有$的行打印出來
6.顯示整個檔案(只需將範圍設定為1到最後於一行)
$代表最後一行
sed -n ‘1,$p’ file
7.任意字元 ,模式/.*/,如/.*ing/匹配任意以ing結尾的單詞
sed -n ‘/.*ing/’p file
8.列印首行
sed -n ‘1p’ file
9.列印尾行
sed -n ‘$p’ file