[shell] awk学习
awk处理最后一行
awk '{if(NR>1)print a;a=$0}END{print a="b"}' file awk 'BEGIN{getline a}{print a;a=$0}END{print a="b"}' file
awk域匹配
echo "12 34" | awk '$1 ~ /1/' echo "12 34" | awk '$1 ~ "1"' 如果把域放后面,记得字符串多的放~前面 echo "12 34" | awk '"123" ~ $1' echo "12 34" | awk '"1" ~ $1' #没结果
打印九九乘法法
awk 'BEGIN{for(n=1;n<=9;n++){for(i=1;i<=n;i++){printf i"x"n"="i*n" "}print}}' 每行后面多了一个空格 awk 'BEGIN{for(n=1;n<=9;n++){for(i=1;i<=n;i++){end=i==n?"\n":" ";printf i"x"n"="i*n end}}}'
求最大值、最小值
awk 'max<$1{max=$1}END{print max}' file awk '{min=(min=="" || min>$1)?$1:min}END{print min}' file
头尾不变,中间行改动
awk '{a[NR]=$0}END{print a[1];for(i=2;i<NR;i++){print a[i]"a"}print a[i]}' file awk '{a[NR]=$0}END{for(i=1;i<=NR;i++){if(i==1||i==length(a))print a[i];else print a[i]"a"}}' file sed '1n;$n;s/$/a/' file awk 'NR==1{print;next}{if(a)print a;a=$0"a"}END{print $0}' file awk -vn=`grep -c . file` 'NR!=1&&NR!=n{$0=$0"a"}1' file
[root@66a awk]# cat file "a":"1","b":"2","c":"3","d":"4","e":"5" "a":"1","b":"2","d":"4" "c":"3","e":"5" [root@66a awk]# awk -f what.sh file abcde 12345 12#4# ##3#5 [root@66a awk]# cat what.sh BEGIN{FS="[:,]"} {gsub(/"/,"")} NR==1{ for(i=1;i<=NF;i+=2){printf $i;a[++n]=$i}; print "" } { for(i=1;i<=NF;i+=2)b[$i]=$(i+1); for(i=1;i<=n;i++){ if(a[i] in b)printf b[a[i]]; else printf "#"} print ""; delete b }
[root@66a awk]# cat a1 1 21 3 22 5 12 [root@66a awk]# cat a2 3 27 5 32 [root@66a awk]# cat a3 1 23 5 12 [root@66a awk]# awk -f what.sh a* id a1 a2 a3 1 21 0 23 3 22 27 0 5 12 32 12 [root@66a awk]# cat what1.sh { a[$1","FILENAME]=$2; b[$1]; } END{ printf "id"; for(i=1;i<ARGC;i++)printf "\t"ARGV[i]; print ""; c=asorti(b); for(i=1;i<=c;i++){ s=b[i]; for(j=1;j<ARGC;j++){ s=a[b[i]","ARGV[j]]?s"\t"a[b[i]","ARGV[j]]:s"\t0" } print s; } } [root@66a awk]# cat what2.sh ARGV[1]==FILENAME{c[++n]=$1} { a[$1","FILENAME]=$2 } END { printf "id"; for(i=1;i<ARGC;i++)printf "\t"ARGV[i]; print ""; for (i=1;i<=n;i++) { s=c[i]; for (j=1;j<ARGC;j++){ if(c[i]","ARGV[j] in a)s=s"\t"a[c[i]","ARGV[j]]; else s=s"\t0"; } print s; } }