awk 常用示例
获取本机 IP 方式
/sbin/ifconfig |awk -v RS="Bcast:" '{print $NF}'|awk -F: '/addr/{print $2}' # 直接获取当前 IP 地址 /sbin/ifconfig |awk '/inet/&&$2!~"127.0.0.1"{split($2,a,":");print a[2]}' # 也是 直接获取当前 IP 地址 /sbin/ifconfig |awk -v RS='inet addr:' '$1!="eth0"&&$1!="127.0.0.1"{print $1}'|awk '{printf"%s|",$0}' # 输出 网卡名称 和当前配置IP 地址 /sbin/ifconfig |awk '{printf("line %d,%s ",NR,$0)}' # 默认是 输出所有的网卡信息 # 可以直接指定网卡或者定义类型(%d数字,%s字符)
看磁盘空间方式
df -h|awk -F"[ ]+|%" '$5>14{print $5}' # 使用量 百分比 df -h|awk 'NR!=1{if ( NF == 6 ) {print $5} else if ( NF == 5) {print $4} }' # 依次分行显示各个分区的使用 百分百比 df -h|awk 'NR!=1 && /%/{sub(/%/,"");print $(NF-1)}' # 依然依次显示 各个分区使用量的百分比 df -h|sed '1d;/ /!N;s/ //;s/ +/ /;' # df -h 精简显示 # 将磁盘分区整理成一行 可直接用 df -P
排列打印
awk 'END{printf "%-10s%-10s %-10s%-10s %-10s%-10s ","server","name","123","12345","234","1234"}' txt awk 'BEGIN{printf "|%-10s|%-10s| |%-10s|%-10s| |%-10s|%-10s| ","server","name","123","12345","234","1234"}' awk 'BEGIN{ print " *** 开 始 *** "; print "+-----------------+"; printf "|%-5s|%-5s|%-5s| ","id","name","ip"; } $1!=1 && NF==4{printf "|%-5s|%-5s|%-5s| ",$1,$2,$3" "$11} END{ print "+-----------------+"; print " *** 结 束 *** " }' txt