0
点赞
收藏
分享

微信扫一扫

awk-I/O语句

getline 读取下一个输入记录设置给$0

getline var 读取下一个输入记录并赋值给变量var

command | getline [var] 运行shell命令管道输出到$0或var

next 停止当前处理的输入记录后面运作

print 打印当前记录

printf fmt,expr-list 格式化输出

printf fmt,expr-list > file 格式化输出和写到文件

system(cmd-line) 执行命令和返回状态

print ...>>file 追加输出到文件

print ...| command 打印输出作为命令输入

1.

getline

获取匹配的下一行

[root@study ~]# seq 5|awk '/3/{getline;print}'
4
#
[root@study ~]# seq 5|awk '/3/{print;getline;print}'
3
4

在匹配的下一行加个星号

[root@study ~]# seq 5|awk '/3/{getline;sub(".*","&*");print}'
4*
[root@study ~]# seq 5|awk '/3/{getline;sub(".*","&*")}{print}'
1
2
4*
5

把a文件的行追加到b文件的行尾

[root@study ~]# cat a b 
a
b
c
1 one
2 two
3 three
[root@study ~]# awk '{getline line <"a";print $0,line}' b
1 one a
2 two b
3 three c
#把a文件的行替换b文件的指定字段
[root@study ~]# awk '{getline line <"a";gsub($2,line,$2);print}' b
1 a
2 b
3 c
#把a文件的行替换b文件的对应字段
[root@study ~]# awk '{getline line <"a";gsub("two",line,$2);print}' b
1 one
2 b
3 three

command | getline [var]

#获取执行shell命令后结果的第一行:
[root@study ~]# awk 'BEGIN{"seq 5"|getline var;print var}'
1
#循环输出执行shell命令后的结果:
[root@study ~]# awk 'BEGIN{while("seq 5"|getline)print}'
1
2
3
4
5

2.

next

# #不打印匹配行
[root@study ~]# seq 5 |awk '{if($0==3){next}else{print}}'
1
2
4
5
# #删除指定行
[root@study ~]# seq 5 |awk 'NR==1{next}{print $0}'
2
3
4
5
[root@study ~]# seq 5 |awk 'NR==1{next}{print}'
2
3
4
5
# #把第一行内容放到每行的前面:
[root@study ~]# cat a
hello
1 a
2 b
3 c
[root@study ~]# awk 'NR==1{s=$0;next}{print s,$0}' a
hello 1 a
hello 2 b
hello 3 c
[root@study ~]# awk 'NR==1{s=$0}NF!=1{print s,$0}' a
hello 1 a
hello 2 b
hello 3 c

3.

system()

[root@study ~]# #执行shell命令判断返回值
[root@study ~]# awk 'BEGIN{if(system("grep root /etc/passwd &> /dev/null")==0)print "yes";else print "no"}'
yes

4.

打印结果输出到文件

[root@study ~]# tail -n5 /etc/services |awk '{print $2>"a.txt"}'
[root@study ~]# cat a.txt
48556/tcp
48556/udp
48619/tcp
48619/udp
49000/tcp

5.

管道连接shell命令

[root@study ~]# tail -5 /etc/services |awk '{print $2|"grep tcp"}'
48556/tcp
48619/tcp
49000/tcp



举报

相关推荐

0 条评论