linux命令之awk(gawk)


linux程序之awk(gakw)


gawk程序是Unix中的原始awk程序的GNU版本,gawk程序让流编辑迈上了一个新台阶,他提供了一种编程语言而不只是编辑命令.

gawk可以做的事:
1.定义变量来保存数据
2.使用算术和字符串操作符来处理数据
3.使用结构化编程概念(if-then语句和循环)来为数据处理增加处理逻辑;
通过提取数据文件中的数据元素,将其重新排列格式化,生成格式化报告


gawk基础

1) gawk程序的基本格式
gawk options program file

选项

-F fs                  指定行中划分数据字段的字段分隔符
-f file                 从指定的文件中读取程序
-v var=value    定义gawk程序中一个变量及其默认值
-mf N              指定要处理的数据文件中的最大字段数
-mr N              指定要处理的数据文件中的最大数据行
-W keyword    指定gawk的兼容模式或警告等级
2) 从命令行读取程序脚本

gawk程序脚本用一对花括号来定义.

gawk '{print "hello world!"}'  # 输入后什么都不会输出,应为没有指定文件名,如果你输入一行文本并按下回车,gawk会对这行文本运行一遍程序脚本,进而打印.
# hello world!
3) 使用数据字段变量

gawk的主要特性之一是其处理文本文件中数据的能力.他会自动给一行中的每个数据元素分配一个变量.
默认情况下:

$0  代表整个文本行
$1  代表文本行中的第1个数据字段
$2  代表文本行中的第2个数据字段
$n  代表文本行中的第n个数据字段

示例:
data.txt

this is line 1
this is line 2
this is line 3
this is line 4
this is line 5
gawk '{print $1}' data.txt
# 输出
this
this
this
this
this

如果要读取其他字段分隔符的文件,可以使用-F指定

gawk -F ':' '{print $1,$2}' /etc/passwd

# 输出
root x
bin x
daemon x
adm x
lp x
sync x
shutdown x
halt x
mail x
operator x
games x
ftp x
nobody x
systemd-network x
dbus x
polkitd x
sshd x
postfix x
chrony x
ntp x
tcpdump x
nscd x
mysql x
4) 在程序脚本中使用多个命令

多个命令之间使用分号(;)分割.使用次提示符一次一行输入程序可以不用(>)

echo "my name is wyh" | gawk '{$4="wang"; print $0}' 
# my name is wang
5) 从文件中读取程序

跟sed一样,gwak编辑器可以允许将程序存储到文件中,然后再在命令行中引用

scripts.gawk

{print $1 "'s home directory is " $6}
gawk -F ':' -f script.gawk /etc/passwd

------输出
root's home directory is /root
bin's home directory is /bin
daemon's home directory is /sbin
adm's home directory is /var/adm
lp's home directory is /var/spool/lpd
sync's home directory is /sbin
shutdown's home directory is /sbin
halt's home directory is /sbin
mail's home directory is /var/spool/mail
operator's home directory is /root
games's home directory is /usr/games
ftp's home directory is /var/ftp
nobody's home directory is /
systemd-network's home directory is /
dbus's home directory is /
polkitd's home directory is /
sshd's home directory is /var/empty/sshd
postfix's home directory is /var/spool/postfix
chrony's home directory is /var/lib/chrony
ntp's home directory is /etc/ntp
tcpdump's home directory is /
nscd's home directory is /
mysql's home directory is /var/lib/mysql

可以在程序文件中指定多条命令,每条命令放一行,不需要分号,否则需要.
在程序中定义变量,赋值即定义,引用直接使用变量名
script3.gawk

{
test ="'s home directory is"
print $1 text $6
}
6) 在处理数据前后运行脚本
gawk 'BEGIN {print "Start of file"}; {print $0}; END { print "End of file"}' data.txt

----------输出
Start of file
this is line 1
this is line 2
this is line 3
this is line 4
this is line 5
End of file
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值