三,从文件输入
1,
格式:
gawk '/匹配字符串/'
gawk '{处理动作}'
gawk '/ 匹配字符串/ {处理动作}' 文件名
2,
[root@rhel helinbash]# gawk '/root/' /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@rhel helinbash]# grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@rhel helinbash]#
3,
[root@rhel helinbash]# gawk '/^root/' /etc/passwd
root:x:0:0:root:/root:/bin/bash
[root@rhel helinbash]#
4,
[root@rhel helinbash]# gawk '/^root/'
root
root
root
root
studnet
t^H^[[3~^H^H^H this is a demo string wih^H^H iclcude root key woard
root hello abc
root hello abc
[root@rhel helinbash]#
注:红色的字体是过滤后的输出,这个是gawk的交互式执行命令
5,
[root@rhel helinbash]# gawk -F: '{ print $1 $3 }' /etc/passwd
root0
bin1
daemon2
adm3
lp4
sync5
shutdown6
halt7
mail8
news9
uucp10
operator11
games12
gopher13
ftp14
nobody99
nscd28
vcsa69
rpc32
mailnull47
smmsp51
pcap77
ntp38
dbus81
avahi70
sshd74
rpcuser29
nfsnobody65534
haldaemon68
avahi-autoipd100
xfs43
gdm42
sabayon86
Oracle500
named25
[root@rhel helinbash]#
6,
[root@rhel helinbash]# gawk -F: '/root/{ print $1 $3 }' /etc/passwd
root0
operator11
[root@rhel helinbash]#
7,
格式化输出print函数
awk命令操作处理部分是放在“{}”(括号)中;print函数将变量和字符夹杂着输出。 如同linux中的echo命令
二,从命令输入
1,
awk还可以处理通过管道接收到的linux命令的结果,shell程序通常使用awk做深处理。
(1)
格式:
命令| gawk '/匹配字符串/'
命令| gawk '{处理动作}'
命令| gawk '/匹配字符串/ {处理动作}'
(2)
[root@rhel helinbash]# date
Mon May 26 10:10:01 CST 2014
[root@rhel helinbash]# date | gawk '{print "Month:"$2"\nYear:",$6 }'
Month:May
Year: 2014
[root@rhel helinbash]#
(3)注意上面的例子,一种是直接在Month后连接$2,另一种是在Year和$6之间使用了逗号,都由OFS决定。
本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-05/102520.htm
