搞定文本处理!AWK(gawk)基础教程,带你快速上手文本三剑客之一!
共 3687字,需浏览 8分钟
·
2024-10-28 18:23
1 gawk命令格式
gawk option program file
	选项:		描述
	-F fs			指定行中划分数据字段的字段分隔符
	-f file			从指定的文件中读取程序
	-v var=value		定义gawk程序中的一个变量及其默认值
	-mf N			指定要处理的数据文件中的最大字段数
	-mr N			指定数据文件中的最大数据行数
	-W  keyword		指定gawk的兼容模式或警告等级
  
  2 从命令行读取程序脚本
        [root@centos7 ~]# gawk '{print "Hello World!"}'
  
  [root@centos7 ~]# gawk '{print "Hello World!"}'
Thie is a error test
Hello World!
Hello World!
Hello World!
  
  3 使用数据字段变量
$0	代表整个文本行
$1	代表文本行的第一个数据段
$n	代表文本行的第n个数据段
  
  [root@centos7 ~]# gawk -F : '{print $1}' /etc/passwd
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
operator
[……]
  4 在程序脚本中使用多个命令
[root@centos7 ~]# echo "My name is centos"|gawk '{$4="hahaha";print $0}'
My name is hahaha
  
  5 从文本中读取程序
[root@centos7 ~]# cat script2.gawk 
{print $1 "'s' home directory is " $6}
[root@centos7 ~]# gawk -F: -f script2.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
[……]
  
  [root@centos7 ~]# cat script3.gawk 
{
text = "'s home directory is "
print $1 text $6
}
  [root@centos7 ~]# gawk -F: -f script3.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
[……]
  
  6 在处理数据前运行脚本
[root@centos7 ~]# cat data3.txt 
Line 1
Line 2
Line 3
[root@centos7 ~]# gawk 'BEGIN{print "The data3 File contents:"}{print $0}' data3.txt The data3 File contents:
Line 1
Line 2
Line 3
  
  7 在处理数据后运行脚本
[root@centos7 ~]# gawk '{print $0} END{print "End of file"}' data3.txt 
Line 1
Line 2
Line 3
End of file
  
  链接:https://www.cnblogs.com/Sunzz/p/7232058.html
(版权归原作者所有,侵删)
评论
