Shell脚本中的正则表达式(4)

通常情况下awk所使用的命令格式如下所示,其中,单引号加上大括号“{}”用于设置对数据进行的处理动作。awk可以直接处理目标文件也可以通过“-f”读取脚本对目标文件进行处理。

awk 选项 '模式或条件 {编辑指令}' 文件1 文件2 ...... awk -f 脚本文件 文件1 文件2 ...

awk包含几个特殊的内建变量(可直接用)如下所示:

NF:当前处理的行的字段个数。

FS:指定每行文本的字段分隔符,默认为空格或制表位。

NR:当前处理的行的字段个数。

$0:当前处理的行的整行内容。

FILENAME:被处理的文件名。

RS:数据记录分隔,默认为\n,即每行为一条记录。

2)用法示例 [root@centos01 ~]# awk '{print}' test.txt <!--输出所有内容--> he was short and fat. He was wearing a blue polo shirt with black pants. The home of Football on BBC Sport online. the tongue is boneless but it breaks bones.12! google is the best tools for search keyword. The year ahead will test our political establishment to the limit. PI=3.141592653589793238462643383249901429 a wood cross! Actions speak louder than words #woood # #woooooood # AxyzxyzxyzxyzC I bet this place is really spooky late at night! Misfortunes never come alone/single. I shouldn't have lett so tast. [root@centos01 ~]# awk 'NR==1,NR==3{print}' test.txt <!--输出1~3行内容--> he was short and fat. He was wearing a blue polo shirt with black pants. The home of Football on BBC Sport online. [root@centos01 ~]# awk '(NR%2)==1{print}' test.txt <!--输出所有奇数行的内容--> he was short and fat. The home of Football on BBC Sport online. google is the best tools for search keyword. PI=3.141592653589793238462643383249901429 Actions speak louder than words #woood # #woooooood # I bet this place is really spooky late at night! I shouldn't have lett so tast. [root@centos01 ~]# awk '(NR%2)==0{print}' test.txt <!--输出所有偶数行内容--> He was wearing a blue polo shirt with black pants. the tongue is boneless but it breaks bones.12! The year ahead will test our political establishment to the limit. a wood cross! AxyzxyzxyzxyzC Misfortunes never come alone/single. [root@centos01 ~]# awk '/^root/{print}' /etc/passwd <!--输出以root开头的行--> root:x:0:0:root:/root:/bin/bash [root@centos01 ~]# awk '{print $1 $3}' test.txt <!--输出每行中的第1、3个字段--> heshort Hewearing Theof theis googlethe Theahead PI=3.141592653589793238462643383249901429 across! Actionslouder #woood #woooooood AxyzxyzxyzxyzC Ithis Misfortunescome Ihave

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

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