前言
这些案例是我收集起来的,大多都是我自己遇到过的,有些比较经典,有些比较具有代表性。这些awk案例我也录了相关视频的讲解awk经典实战案例精讲。
awk插入几个新字段
在”a b c d”的b后面插入3个字段e f g。echo a b c d|awk '{$3="e f g "$3}1'
awk格式化空白
移除每行的前缀、后缀空白,并将各部分左对齐。aaaa bbb ccc
bbb aaa ccc
ddd fff eee gg hh ii jjawk 'BEGIN{OFS="\t"}{$1=$1;print}' a.txt
执行结果:aaaa bbb ccc
bbb aaa ccc
ddd fff eee gg hh ii jj
awk筛选IPv4地址
从ifconfig命令的结果中筛选出除了lo网卡外的所有IPv4地址。## 1.方法一:
ifconfig | awk '/inet / && !($2 ~ /^127/){print $2}'
# 按段落读取
## 2.方法二:
ifconfig | awk 'BEGIN{RS=""}!/lo/{print $6}'
## 3.方法三:
ifconfig |\
awk '
BEGIN{RS="";FS="\n"}
!/lo/{$0=$2;FS=" ";$0=$0;print $2}
'
awk读取.ini配置文件中的某段[base]
name=os_repo
baseurl=https://xxx/centos/$releasever/os/$basearch
gpgcheck=0
enable=1
[mysql]
name=mysql_repo
baseurl=https://xxx/mysql-repo/yum/mysql-5.7-community/el/$releasever/$basearch
gpgcheck=0
enable=1
[epel]
name=epel_repo
baseurl=https://xxx/epel/$releasever/$basearch
gpgcheck=0
enable=1
[percona]
name=percona_repo
baseurl = https://xxx/percona/release/$releasever/RPMS/$basearch
enabled = 1
gpgcheck = 0awk '
BEGIN{RS=""} # 按段落
/\[mysql\]/{
print;
while((getline)>0){
if(/\[.*\]/){
exit
}
}
}
' a.txt
awk根据某字段去重
去掉uid=xxx重复的行。2019-01-13_12:00_index?uid=123
2019-01-13_13:00_index?uid=123
2019-01-13_14:00_index?uid=333
2019-01-13_15:00_index?uid=9710
2019-01-14_12:00_index?uid=123
2019-01-14_13:00_index?uid=123
2019-01-15_14:00_index?uid=333
2019-01-16_15:00_index?uid=9710awk -F"?" '!arr[$2]++{print}' a.txt
结果:2019-01-13_12:00_index?uid=123
2019-01-13_14:00_index?uid=333
2019-01-13_15:00_index?uid=9710
awk次数统计portmapper
portmapper
portmapper
portmapper
portmapper
portmapper
status