目录
1、print
测试文件内容
this is 1 line222
this is 2 line
this is 3 line.
this is 4 line,hello world
(1)print最后一个$NF
awk '{print $NF}' test.txt
# 输出倒数第二列(不能越界)
awk '{print $(NF-1)}' test.txt
(2)print全部
awk '{print $0}' test.txt
(3)格式化输出
%代表后面的变量,这里两个%代表$1,$NF
awk '{printf "%-25s %-10s\n",$1,$NF}' test.txt
2、-F
awk -F , '{print $1}' test.txt #用,号作为分隔符
awk -F [ ,] '{print $1}' test.txt #用空格和,号作为分隔符
3、设置变量-v
#变量a=1,$3都是数字,在做运算+1,如果非数字会默认为0
# 多个变量设置,$1是字符串,拼接变量b
awk -va=1 '{print $3,$3+a}' test.txt
awk -va=1 -vb=s '{print $1b,$3+a}' test.txt
输出结果:
4、运算符
(1)找到第三列$3>2的行
awk '$3>2' test.txt
(2)找到第一列为this的行
awk '$1="this"' test.txt
(3)找到最后一行为line.
awk '$NF=="line."' test.txt
(4)不等于
awk '$NF!="line."' test.txt
(5)最后一列不等于line.且第三列大于2
awk '$NF!="line." && $3>2' test.txt
(6)最后一列等于line.或者第三列小于等于2
awk '$NF=="line." || $3<=2' test.txt
(7)判断倒数第二列==1的行,这里括号注意使用
awk '{if( $(NF-1) == 1) {print $0}}' test.txt
5、内建变量
# BEGIN后面是表头信息,自己构建的所有内建变量在BEGIN中用了“”,表示字符串本身
(1)awk 'BEGIN{printf "%4s %4s %4s %4s %4s %4s %4s %4s %4s\n","FILENAME","ARGC","FNR","FS","NF","NR","OFS","ORS","RS";printf "---------------------------------------------\n"} {printf "%4s %4s %4s %4s %4s %4s %4s %4s %4s\n",FILENAME,ARGC,FNR,FS,NF,NR,OFS,ORS,RS}' test.txt
(2)awk -F\' 'BEGIN{printf "%4s %4s %4s %4s %4s %4s %4s %4s %4s\n","FILENAME","ARGC","FNR","FS","NF","NR","OFS","ORS","RS";printf "---------------------------------------------\n"} {printf "%4s %4s %4s %4s %4s %4s %4s %4s %4s\n",FILENAME,ARGC,FNR,FS,NF,NR,OFS,ORS,RS}' test.txt
(3)awk '{print NR,FNR,$1,$2,$3}' test.txt
(4)awk '{print NR,FNR,$1,$2,$3}' test.txt test1.txt
(5)awk '{print $1,$2,$5}' OFS=" $ " test.txt
6、正则匹配
输出第五列包含 "world",并打印第二列与第四列, ~表示开始匹配,//之间是表达式(1)awk '$5 ~ /world/ {print $2,$4}' test.txt
(2)awk 'BEGIN{IGNORECASE=1} /this/' test.txt # 忽略大小写
awk 'BEGIN{IGNORECASE=1} $1 ~ /this/' test.txt
(3)awk 'BEGIN{IGNORECASE=1} $1 !~ /r/' test.txt #第一列不包含r的行
7、BEGIN 和 END
- BEGIN{ 这里面放的是执行前的语句 }
- END {这里面放的是处理完所有的行后要执行的语句 }
测试文件 test1.txt
Marry 2143 78 84 77 Jack 2321 66 78 45 Tom 2122 48 77 71 Mike 2537 87 97 95 Bob 2415 40 57 62脚本文件 test.awk
#!/bin/awk -f #运行前 BEGIN { math = 0 english = 0 computer = 0 printf "NAME NO. MATH ENGLISH COMPUTER TOTAL\n" printf "---------------------------------------------\n" } #运行中 { math+=$3 english+=$4 computer+=$5 printf "%-6s %-6s %4d %8d %8d %8d\n", $1, $2, $3,$4,$5, $3+$4+$5 } #运行后 END { printf "---------------------------------------------\n" printf " TOTAL:%10d %8d %8d \n", math, english, computer printf "AVERAGE:%10.2f %8.2f %8.2f\n", math/NR, english/NR, computer/NR }
8、找到文件中长度范围
awk 'length>80' log.txt
9、统计文件大小
ls -l *.txt | awk '{sum+=$5} END {print sum}'
10、awk的条件循环语句