awk 常用语法
发表于|更新于
|字数总计:610|阅读时长:3分钟
AWK 常用命令总结
概述
此文章为总结awk常用命令而设,方便以后查找。
求和
[root@master scripts]# awk 'NR==1{a=$1} NR==2{b=$1} END {print b+a}' a 3 [root@master scripts]# cat a 1 2
|
awk 乘除
free | awk -F "[ ]+" 'NR==2 {printf ("%.2f%\n", $3/$2*100)}'
|
printf 格式化输出
[root@master ~]# awk -F ":" 'BEGIN{print"用户名\t\t\t字段1\t\t 字段2\t\t 权限"}/sbin:/{printf "user:%-20s%-20s%-20s%-20s\n", $1,$4,$5,$7}' /etc/passwd 用户名 字段1 字段2 权限 user:daemon 2 daemon /sbin/nologin user:sync 0 sync /bin/sync user:shutdown 0 shutdown /sbin/shutdown user:halt 0 halt /sbin/halt
|
求最大值
[root@master ~]# k describe nodes | awk -F "[ ()%]+" '/cpu /{print $4}' 42 5 15
[root@master ~]# k describe nodes | awk -F "[ ()%]+" 'BEGIN{ max = 0} /cpu / {if ($4 > max) max = $4 ; fi} END{print max}' 42
|
求最小值
求最小值的时候需要注意,min的初始值需要设置为一个大数,最好大于所有数的最大值。如果min被设为初始值0,那下面的结果将是错误的。
cat data 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0
|
awk 'BEGIN{min = 65535} {if ($1 < min) min = $1;fi} END{printf "Min = %.1f\n",min}' data
|
求平均值
awk '{sum += $1} END {printf "NR = %d,Average = %3.3f\n",NR,sum/NR}' data
|
awk if 判断
awk '{ if($3 <= 30) { print "The salary of ",$1, " is ", $4, "\n" } elseif($3 <= 40) { print "The salary of ",$1, " is ", $4, "\n" } else{ print "The salary of ",$1, " is ", $4, "\n" } }' employee.txt
|
awk 输出不换行
awk 统计socket状态
netstat -ant | awk '/^tcp/ {++y[$NF]} END {for(w in y) print w, y[w]}'
|
awk 组合的命令 打印 + 执行
kubectl get pods -A | grep default | awk '{cmd="kubectl -n " $1 " logs " $2; print cmd; system(cmd)}'
|
awk 配合 kubectl
kubectl get deployments,sts -A -o=custom-columns=NS:.metadata.namespace,KIND:.kind,NAME:.metadata.name,Replicas:.spec.replicas | awk 'BEGIN {OFS="\t"} NR==1 || ($4=="1" && $1 !~ /kube-system|monitoring|tekton-pip|operators|huawei-csi|cert-manager/ && !/mysqlha|tonggtp|dongfangtong/)'
|