awk
如获取80端口使用情况
lsof -i:80 | awk '{print $2}'
需要去过滤掉第一行,NR 指定行:
lsof -i:80 | awk 'NR!=1{print $2}'
每行按空格或TAB分割,输出文本中的1、4项
# 格式化输出
$ awk '{printf "%-8s %-10s\n",$1,$4}' log.txt
# 列转行,拼接 1,2,3,4,5,
awk '{printf "%s,",$1}' a1.txt
忽略大小写
~ 表示模式开始。// 中是模式。
$ awk 'BEGIN{IGNORECASE=1} /this/' log.txt
---------------------------------------------
2 this is a test
This's a test
分隔符
-F 按分隔符分割
cat /etc/passwd |awk -F ':' '{print $1}'
累计
awk '{sum+=$1}END{print sum}'
过滤完排序
cat log.log |awk '{print $12}' |sort |uniq
匹配 与 不匹配
~ 匹配正则
!~ 不匹配正则
== 等于
!= 不等于
[root@centos7_test130]# cat test.txt
qqqqq 1
wwwww 2
eeeee 3
ddddd f
[root@centos7_test130]# cat test.txt |awk '{if($2==1)print}'
qqqqq 1
[root@centos7_test130]# cat test.txt |awk '{if($2!=1)print}'
wwwww 2
eeeee 3
ddddd f
[root@centos7_test130]# cat test.txt |awk '{if($2~/^f/)print}'
ddddd f
[root@centos7_test130]# cat test.txt |awk '{if($2!~/./)print}'