Linux Shell 编程之gawk详解

The name awk comes from the initials of its designers: A lfred V. Aho, Peter J. W einberger, and Brian W. K ernighan. The original version of awk was written in 1977 at AT&T Bell Laboratories.

gawk 简史:

Paul Rubin wrote gawk in 1986. Jay Fenlason completed it, with advice from Richard Stallman. John Woods contributed parts of the code as well. In 1988 and 1989, David Trueman, thoroughly reworked gawk for compatibility with the newer awk.

gawk 是 awk 的 GNU 版本。是一个功能更加强大的具有编程扩展性的工具。

gawk 的命令格式 gawk options  program   file

简单的对 options 做个介绍:

-F fs : 指定航中分割数据字段的字段分隔符 -f file: 指定读取程序的文件名。多行命令可以放在一个文件以便复用 -v var=value:   指定 gawk 程序中一个变量以及其默认值 -mf N:  指定要处理的数据文件中的最大字段数 -mr N:  指定数据文件中的最大数据行数 -W keyword: 指定 gawk 的兼容模式或警告等级 gawk 的命令编程

gawk 的中心是其命令,可以有两种方式来调用命令

命令行的调用方式;

将多行命令编写在文件的调用方式

命令行的调用方式: [root@CentOS00 _data] # gawk '{print "hello, world!"} ' _
要注意的是两点:

'{}' 成为 gawk 的固定格式,{} 是放置 gawk 命令的地方,而'' 是将命令当做字符串与其他选项或参数字符串隔离的分隔符。

[root@centos00 _data] # gawk 'print "hello, world!" ' gawk: cmd. line: 1 print   "hello, world!"  
gawk: cmd. line: 1 : ^ syntax error
[root@centos00 _data] # gawk {print "hello, world!"} bash: !"}: event not found [root@centos00 _data] #

gawk 的默认从标准输入流来读文本,如果没有指定文本文件,那就等待标准输入流的输入:

[ root@ centos00 _data]# gawk  '{print "hello, world!"} ' this  a hello world programm
hello, world!

多条命令也可以写在一行中处理,使用“;”分隔符即可:

[root @centos 00 _data]# gawk -F:  '{ $6 = $1 ":" $6 ; print $1 "' 's home director is " $6 } '  /etc/passwd
roots home director  is  root:/root
bins home director  is  bin:/bin
daemons home director  is  daemon:/sbin
adms home director  is  adm:/ var /adm
lps home director  is  lp:/ var /spool/lpd
syncs home director  is   sync :/sbin

对单引号"'"做转义的时候,使用两次单引号即可,而不是使用"\".

gawk 的功能也是对每行输入做处理。

将多行命令编写在文件的调用方式 [root@centos00 _data] # gawk -F: -f getUserDirectory.awk /etc/passwd [root@centos00 _data] # cat getUserDirectory.awk { print  $ 1   "'s home directory is "  $ 6  }
[root@centos00 _data] # gawk -F: -f getUserDirectory.awk /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

多行命令写在文件中:

[root@centos00 _data] # cat getUserDirectory.awk {$6 = $1  ":"  $6 }
{ print  $1  "'s home directory is "  $6 }
[root@centos00 _data] # gawk -F: -f getUserDirectory.awk /etc/passwd root 's home directory is root:/root
bin'
s  home directory is bin: /bin
daemon's home directory is daemon:/sbin

依然是用{} 来引用命令,但不需要''来分割命令字符串了

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/6b6bc32df5129eccad626573bf4af975.html