Linux awk 命令简单使用

awk 比到目前为止一直讨论的工具都强大得多。
它是一种完整的语言,是一种解析脚本语言。换句话说,在运行它们之前,不需要编译用 awk 编写的程序。在此将给出几个简单的 awk 语句,只作为命令行的应用。可以看到,它常常在系统 shell 脚本中使用(通常也作为一个简单的单行命令),而且知道它的存在必定有用。但是如果希望 awk 能够很好地完成事情(根据程序的规则,选择和替换文本文件中的文本),应该考虑任务是否可以通过另一种更强大的脚本语言,更简单、更容易地完成(例如 Python 或 Perl)。
另一方面, awk 是一个总可使用的小得多的程序:

user@bible:~ > [color=blue][b]cat foods[/b][/color]
boiled carrots
fried potatoes
grilled onions
grated carrot

user@bible:~ > [b][color=blue]awk /carrot/ foods[/color][/b]
boiled carrots
grated carrot
在此,awk 只选择匹配 carrot 的行

user@bible:~ > [b][color=blue]awk '{print $1}' foods[/color][/b]
boiled
fried
grilled
grated
在此,awk 打印了每一行的第一个字段,正如 “{print $1}”的定义。使用 $2 得到第二个字段,而 $0 表示整行。


user@bible:~ >[color=blue][b]awk -F\: '{print $}' /etc/passwd[/b][/color]
root
bin
[...]
Guest User
也可以定义分隔符为其他字符。以上示例中,选项 -F\: 定义字段分隔符是冒号,允许从/etc/passwd选择一个特定字段(第5个,它是用户的真实名称),它是一个用冒号分隔的文件。


[color=red][b]awk 有多个有用的内置函数。[/b][/color]例如:
user@bible:~ > [color=blue][b]cat morefoods[/b][/color]
biled carrots and fried bacon
fried potatoes and grilled sausages and mushrooms
grilled onions
grated carrot

user@bible:~ > [color=blue][b]awk 'NF > 2' morefoods[/b][/color]
boiled carrots and fried bacon
fried potatoes and grilled sausages and mushrooms
[color=red]NF 表示字段的数量。[/color]在这个示例中,通过使用 'NF>2',选择了超过两个字段的行。
常用的解决问题之处:
试解决将结构化数据导入到应用程序的问题,其中一些行有错误数量的字段,而导入失败,等等。

user@bible:~ > [color=blue][b]awk 'NF > 2 {print $4}' morefoods[/b][/color]
fried
grilled
在此,awk 打印了每行的第4个字段,它有两个以上的字段。

user@bible:~ > [color=blue][b]awk '{print NF ":" $0}' morefoods[/b][/color]
5:biled carrots and fried bacon
7:fried potatoes and grilled sausages and mushrooms
2:grilled onions
2:grated carrot
在此,awk 打印字段的数量,之后是一个冒号和整行(由 $0 表示)。

awk 脚本可以从命令行运行,使用[color=blue][b] awk -f scriptname.file [/b][/color]这样的命令即可。
例如,将以下内容保存为 script.awk :
{print $1 ":" $2 ":" NF
}
END{print NR}
然后,完成以下事情:
user@bible:~ > [color=blue][b]awk -f script.awk morefoods[/b][/color]
boiled:carrots:5
fried:potatoes:7
grilled:onions:2
grated:carrot:2
4
文件每一行的前两个字段已经打印,它们之间是一个冒号,之后是另一个冒号和该行中的[color=red]字段数量(NF)。[/color]遍历完文件之后,END 字节打印[color=red] NR(记录数量)[/color]的值。


在系统上,GNU awk 提供了 info 文件格式的文档,输入 info awk 可查看它。最新版本的 GNU awk 手册可从 [url]http://www.gnu.org/software/gawk/manual/[/url]得到。


摘自:《SUSE Linux 10 宝典》人民邮电出版社
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值