1、創建測試數據
[root@linuxprobe test]# seq -w 24 | xargs -n 4 | awk '{print "<"NR,$0}' > a.txt ## 創建測試數據
[root@linuxprobe test]# cat a.txt
<1 01 02 03 04
<2 05 06 07 08
<3 09 10 11 12
<4 13 14 15 16
<5 17 18 19 20
<6 21 22 23 24
2、提取特定列
[root@linuxprobe test]# awk '{print $2}' a.txt ## awk讀取數據的默認分隔符是空格,提取第二列 01
05
09
13
17
21 [root@linuxprobe test]# awk '{print $2,$4}' a.txt ##提取第二列和第四列,不同字段間用逗號隔開,默認輸出分隔符為空格 01 03
05 07
09 11
13 15
17 19
21 23 [root@linuxprobe test]# awk '{print $4,$2,$1}' a.txt ## 變換列的順序 03 01 <1
07 05 <2
11 09 <3
15 13 <4
19 17 <5
23 21 <6 [root@linuxprobe test]# awk '{print $NF}' a.txt ## 提取最后一列,NF是awk的內置變量,記錄每一行分割的字段數,最后一個字段即是最后一列 04
08
12
16
20
24 [root@linuxprobe test]# awk '{print $(NF-1)}' a.txt ## 同理,提取倒數第二列 03
07
11
15
19
23
3、指定讀入數據和輸出數據的分割符
[root@linuxprobe test]# sed 's/ /,/g' a.txt -i ## 改變測試數據,將空格替換為逗號 [root@linuxprobe test]# cat a.txt <1,01,02,03,04
<2,05,06,07,08
<3,09,10,11,12
<4,13,14,15,16
<5,17,18,19,20
<6,21,22,23,24 [root@linuxprobe test]# awk '{print $2}' a.txt ## awk默認以空格為讀入分割符,僅有1列 [root@linuxprobe test]# awk -F "," '{print $2}' a.txt ## 利用 -F選項 指定逗號為分割符,提取第二列 01
05
09
13
17
21 [root@linuxprobe test]# awk -F "," '{print $2,$5}' a.txt ## 同上 01 04
05 08
09 12
13 16
17 20
21 24 [root@linuxprobe test]# awk 'FS = "," {print $1}' a.txt ## ??? <1,01,02,03,04
<2
<3
<4
<5
<6 [root@linuxprobe test]# awk 'BEGIN{FS = ","}{print $1}' a.txt ## 定價與 -F <1
<2
<3
<4
<5
<6
4、指定輸出分隔符
[root@linuxprobe test]# cat a.txt <1,01,02,03,04
<2,05,06,07,08
<3,09,10,11,12
<4,13,14,15,16
<5,17,18,19,20
<6,21,22,23,24 [root@linuxprobe test]# awk -F "," '{print $2,$4,$5}' a.txt ##默認輸出分割符為空格 01 03 04
05 07 08
09 11 12
13 15 16
17 19 20
21 23 24 [root@linuxprobe test]# awk -F "," '{OFS = "\t"} {print $2,$4,$5}' a.txt ## 指定制表符為輸出分隔符 01 03 04
05 07 08
09 11 12
13 15 16
17 19 20
21 23 24 [root@linuxprobe test]# awk -F "," '{OFS = ":"} {print $2,$4,$5}' a.txt ## 指定冒號為輸出分隔符 01:03:04
05:07:08
09:11:12
13:15:16
17:19:20
21:23:24
5、awk添加列
[root@linuxprobe test]# sed 's/,/ /g' a.txt -i ##改變測試數據 [root@linuxprobe test]# cat a.txt <1 01 02 03 04
<2 05 06 07 08
<3 09 10 11 12
<4 13 14 15 16
<5 17 18 19 20
<6 21 22 23 24 [root@linuxprobe test]# awk '{print "xxx",$2}' a.txt ## 添加xxx,用雙引號引起來 xxx 01 xxx 05 xxx 09 xxx 13 xxx 17 xxx 21 [root@linuxprobe test]# awk '{print $3,"yyy",$5}' a.txt ##同上 02 yyy 04
06 yyy 08
10 yyy 12
14 yyy 16
18 yyy 20
22 yyy 24 [root@linuxprobe test]# awk '{print $2,"mmm","nnn",$5,"zzz"}' a.txt ## 同上 01 mmm nnn 04 zzz 05 mmm nnn 08 zzz 09 mmm nnn 12 zzz 13 mmm nnn 16 zzz 17 mmm nnn 20 zzz 21 mmm nnn 24 zzz [root@linuxprobe test]# awk '{print "xxxx",$0}' a.txt ## $0表示當前行的所有 xxxx <1 01 02 03 04 xxxx <2 05 06 07 08 xxxx <3 09 10 11 12 xxxx <4 13 14 15 16 xxxx <5 17 18 19 20 xxxx <6 21 22 23 24 [root@linuxprobe test]# awk '{print NR,$1,$3}' a.txt ## NR是awk的內置變量,用於記錄讀取數據的行數 1 <1 02
2 <2 06
3 <3 10
4 <4 14
5 <5 18
6 <6 22 [root@linuxprobe test]# awk '{print $1,NR,$3}' a.txt ## 同上 <1 1 02
<2 2 06
<3 3 10
<4 4 14
<5 5 18
<6 6 22