awk 'BEGIN{ commands } pattern{ commands } END{ commands }'
首先执行 BEGIN 语句块,只会执行一次。通常用于变量初始化,头行打印一些表头信息,在通过stdin读入数据前就被执行。
每读取一行数据使用 pattern{ commands }循环处理数据。
最后执行 END 语句块,只会执行一次,通常用于统计结果。
# example
cat /etc/passwd |awk -F ':' 'BEGIN {print "name,shell"} {print $1","$7} END {print "blue,/bin/nosh"}'
# file
tee top.txt << "EOF"
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
213123 root 20 0 9584 4060 3344 R 6.2 0.1 0:00.01 top
1275702 tomcat 20 0 999 30596 13976 S 6.2 0.4 741:21.61 metrics
1612431 systemd 20 0 888 7708 103788 S 6.2 9.6 2519:09 k3s
1 systemd 20 0 777 1884 6596 S 0.0 0.1 43:55.21 systemd
EOF
# 格式化输出
# - 左对齐
# %s 字符串
# %d 十进制有符号整数
# %u 十进制无符号整数
awk '{printf "%-8s %-8s %-8s %-18s\n",NR, $1,$2,$12}' top.txt
# 计算结果
awk 'BEGIN {sum=0} {printf "%-8s %-8s %-18s\n", $1, $9, $11; sum+=$9} END {print "cpu sum:"sum}' top.txt
# 外部引用变量
awk -v sum=0 '{printf "%-8s %-8s %-18s\n", $1, $9, $11; sum+=$9} END {print "cpu sum:"sum}' top.txt
# 筛选
awk 'NR>1 && $9>0 {printf "%-8s %-8s %-18s\n",$1,$9,$12}' top.txt
awk 'NR==1 || $2~/tomcat/ {printf "%-8s %-8s %-8s %-18s\n",$1,$2,$9,$12}' top.txt
# action 块筛选
awk '{if($9>0){printf "%-8s %-8s %-8s %-18s\n",$1,$2,$9,$12}}' top.txt
# 数组计算第二列的用户进程数量
awk 'NR!=1{a[$2]++;} END {for (i in a) print i ", " a[i];}' top.txt
# 数组操作
# 获取长度
awk 'BEGIN{info="it is a test";lens=split(info,tA," ");print length(tA),lens;}'
# 循环输出,下标从1开始
awk 'BEGIN{info="it is a test";split(info,tA," ");for(k in tA){print k,tA[k];}}'
awk 'BEGIN{info="it is a test";tlen=split(info,tA," ");for(k=1;k<=tlen;k++){print k,tA[k];tlen;}}'
# 判断 key in array(判断语法为 key in array)
awk 'BEGIN{tB["a"]="a1";tB["b"]="b1";if("c" in tB){print "ok";};for(k in tB){print k,tB[k];}}'
# 删除 key
awk 'BEGIN{tB["a"]="a1";tB["b"]="b1";delete tB["a"];for(k in tB){print k,tB[k];}}'
# 判断字符拆分输出文件
awk 'NR>1 {if($0~/tomcat/){printf "%-8s %-8s %-8s %-18s\n",$1,$2,$9,$12 > "1.txt"}else if($0~/root/){printf "%-8s %-8s %-8s %-18s\n",$1,$2,$9,$12 > "2.txt"}else{printf "%-8s %-8s %-8s %-18s\n",$1,$2,$9,$12 > "3.txt"}}' top.txt
# 删除关键字 memory 的重复行
awk '!seen[$0]++ || !/memory/' values.yaml
# 删除并修改原文件
awk '!seen[$0]++ || !/memory/' values.yaml > tmp && mv -v tmp values.yaml
# 替换 ORS, 去除换行符
awk 'BEGIN{ORS=""};{print $0}' x.txt