用法:awk [options] ‘[pattern]{action}’ [var1=value1 var2=value2 …] file … 或者 awk [options] -f scripts [var1=value1 var2=value2 …] file …
1.对应所有行的指令
例子:/etc/passwd 有多少行就输出多少行
实战:awk -F: ‘{a=1;b=2;print a,b}’ /etc/passwd
2.指定一个行的范围
- /RegExp1/,/RegExp2/
实战:awk -F: ‘/^a/‘ /etc/passwd
3.条件表达式
- 关系运算符: > , < , >= , <= , == , !=
- 字符串或数字比较
- ~ , !~ 模式匹配表达式
实战:awk -F: ‘$3<50{sum+=$3;print $1,$3}END{print “sum=”,sum}’ /etc/passwd
4.
echo -e “1:2:3:4\n5:6:7:8” | awk ‘BEGIN{ORS=”-“;RS=”:”}{print $0}’
5.利用awk处理成绩单
命令:awk ‘BEGIN{print “LNO. Name No. Math Eng Com Total”;math=0;eng=0;com=0;}{math+=$3;eng+=$4;com+=$5;printf “%-8s %-7s %-7s %-7s %7s %7s %7s\n”,NR,$1,$2,$3,$4,$5,$3+$4+$5}END{printf “%-24s %7s %7s %7s %7s\n”,”Total: “,math,eng,com,math+eng+com;printf “%-24s %7s %7s %7s %7s\n”,”Avg”,math/NR,eng/NR,com/NR,(com+eng+math)/NR}’ data_score
6.取字符串中大写的字母
echo “abcABC” | awk ‘{match($0,/[[:upper:]]+/);print RSTART,RLENGTH,substr($0,RSTART,RLENGTH)}’
7.把日期以/ 分割成指定名字的数组
echo “18/01/31” | awk ‘{split($0,date,”/“);print date[1],date[2],date[3]}’