Linux 打印文本部分行內容(前幾行,指定行,中間幾行,跨行,奇偶行,后幾行,最后一行,匹配行)


背景

打印對賬文件最后一行匯總信息,通過釘釘定時發送到運維群。順便總結下 Linux 打印文本部分行內容的各種方法。

測試文本

# 生成測試文本內容
$ seq -f "%02g daodaotest" 1 10 > test.txt

# 查看測試文本內容,並顯示行號
$ cat -n test.txt
     1	01 daodaotest
     2	02 daodaotest
     3	03 daodaotest
     4	04 daodaotest
     5	05 daodaotest
     6	06 daodaotest
     7	07 daodaotest
     8	08 daodaotest
     9	09 daodaotest
    10	10 daodaotest

$ awk '{print NR" "$0}' test.txt
1 01 daodaotest
2 02 daodaotest
3 03 daodaotest
4 04 daodaotest
5 05 daodaotest
6 06 daodaotest
7 07 daodaotest
8 08 daodaotest
9 09 daodaotest
10 10 daodaotest

打印前 N 行內容

# head 打印前 5 行內容
$ head -5 test.txt
$ head -n 5 test.txt

# sed 打印前 5 行內容
$ sed -n '1,5p' test.txt

# awk 打印前 5 行內容
$ awk 'NR<6' test.txt

打印指定行內容

# sed 打印第 5 行內容
$ sed -n '5p' test.txt

# awk 打印第 5 行內容
$ awk 'NR==5' test.txt

# tail 配合 head,打印指定行內容
$ tail -n +5 test.txt | head -1

打印指定范圍行內容

# sed 打印 5~10 行內容
$ sed -n '5,10p' test.txt

# awk 打印 5~10 行內容
$ awk 'NR>4 && NR<11' test.txt

# tail 配合 head,打印 5~10 行內容
$ tail -n +5 test.txt | head -6

打印跨行內容

# sed 打印第 3 行 和 5~7 行內容
$ sed -n '3p;5,7p' test.txt

# awk 打印第 3 行 和 5~7 行內容
$  awk 'NR==3 || (NR>4 && NR<8)' test.txt

打印奇偶行內容

# 打印奇數行內容
## NR 表示行號
$ awk 'NR%2!=0' test.txt
$ awk 'NR%2' test.txt

## i 為變量,未定義變量初始值為 0,對於字符運算,未定義變量初值為空字符串
## 讀取第 1 行記錄,進行模式匹配:i=!0(!表示取反)。! 右邊是個布爾值,0 為假,非 0 為真,!0 就是真,因此 i=1,條件為真打印第一條記錄。
## 讀取第 2 行記錄,進行模式匹配:i=!1(因為上次 i 的值由 0 變成了 1),條件為假不打印。
## 讀取第 3 行記錄,因為上次條件為假,i 恢復初值為 0,繼續打印。以此類推...
## 上述運算並沒有真正的判斷記錄,而是布爾值真假判斷。
$ awk 'i=!i' test.txt

## m~np:m 表示起始行;~2 表示:步長
$ sed -n '1~2p' test.txt

## 先打印第 1 行,執行 n 命令讀取當前行的下一行,放到模式空間,后面再沒有打印模式空間行操作,所以只保存不打印,同等方式繼續打印第 3 行。
$ sed -n '1,$p;n' test.txt
$ sed -n 'p;n' test.txt

# 打印偶數行內容
$ awk 'NR%2==0' test.txt
$ awk '!(NR%2)' test.txt
$ awk '!(i=!i)' test.txt
$ sed -n 'n;p' test.txt
$ sed -n '1~1p' test.txt
$ sed -n '1,$n;p' test.txt

打印最后 N 行內容

# tail 打印后 5 行內容
$ tail -5 test.txt
$ tail -n 5 test.txt

打印最后一行內容

# tail 打印最后一行內容
$ tail -n 1 test.txt

# sed 打印最后一行內容
$ sed -n '$p' test.txt

# awk 打印最后一行內容
$ awk 'END {print}' test.txt

打印匹配行內容

# 打印以 "1" 開頭的行內容
$ sed -n '/^1/p' test.txt
$ grep "^1" test.txt

# 打印不以 "1" 開頭的行內容
$ sed -n '/1/!p' test.txt
$ grep -v "^1" test.txt

# 從匹配 "03" 行到第 5 行內容
$ sed -n '/03/,5p' test.txt

# 打印匹配 "03" 行 到匹配 "05" 行內容
$ sed -n '/03/,/05/p' test.txt

微信公眾號:daodaotest


免責聲明!

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



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