linux awk基本語法命令總結


一、基本用法

文本內容准備

2 this is a test
3 Are you like awk
This's a test
10 There are orange,apple,mongo

用法一:行匹配語句awk ‘'只能使用單引號

實例:每行按空格或TAB分割,輸出文本中的1、4項

[root@master mnt]# cat log.txt |awk '{print $1,$4}'
2 a
3 like
This's 
10 orange,apple,mongo
格式化輸出

[root@master mnt]# cat log.txt |awk '{printf "%-8s %-10s\n",$1,$4}'
2 a
3 like
This's
10 orange,apple,mongo

用法二:-F,指定分隔符

[root@master mnt]# cat log.txt |awk -F ',' '{print $1,$2}'
2 this is a test 
3 Are you like awk 
This's a test 
10 There are orange apple

或者使用內建表量

[root@master mnt]# cat log.txt |awk 'BEGIN{FS=","} {print $1,$2}'
2 this is a test
3 Are you like awk
This's a test
10 There are orange apple

#使用多個分隔符,先使用空格分割,然后對分割結果再使用“,”分割

[root@master mnt]# cat log.txt |awk -F '[ ,]' '{print $1,$2,$5}'
2 this test
3 Are awk
This's a
10 There apple

用法三:awk -v #設置變量

[root@master mnt]# cat log.txt |awk -va=1 -vb=s -vc=w '{print $1,$1+a,$1b,$1c}'
2 3 2s 2w
3 4 3s 3w
This's 1 This'ss This'sw
10 11 10s 10w

[root@master mnt]# cat log.txt |awk -va=1 '{print $1,$1+a}'
2 3
3 4
This's 1
10 11

用法四:awk -f {awk腳本} {文件名}

過濾第一列大於2的行
[root@master mnt]# cat log.txt |awk '$1>2' 3 Are you like awk This's a test 10 There are orange,apple,mongo
過濾第一列等於2的行

[root@master mnt]# cat log.txt |awk '$1==2 {print $1,$2}'
2 this

過濾第一列大於2並且第二列等於'Are'的行

[root@master mnt]# cat log.txt |awk '$1>2 && $2=="Are" {print $1,$2}'
3 Are

用法五:指定輸出分割符

[root@master mnt]# cat log.txt |awk '{print $1,$2,$5}' OFS=";" 
2;this;test
3;Are;awk
This's;a;
10;There;

用法六:正則字符串匹配

輸出第二列包含“th” ,並打印第二列與第四列
[root@master mnt]# cat log.txt  |awk '$2 ~ /th/ {print $2,$4}'
this a

~表示模式匹配。//中是匹配的字符串

用法七:忽略大小寫

[root@master mnt]# cat log.txt |awk 'BEGIN{IGNORECASE=1} /THIS/ '
2 this is a test
This's a test

用法八:模式取反

輸出第二列不包含"th"的行的第二列和第四列
[root@master mnt]# cat log.txt |awk '$2 !~ /th/ {print $2,$4}'
Are like
a 
There orange,apple,mongo
等同於

[root@master mnt]# cat log.txt |awk '!/th/ {print $2,$4}'
Are like
a
There orange,apple,mongo

 


免責聲明!

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



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