日期:2014-05-16  浏览次数:20680 次

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

user@bible:~ > cat foods
boiled  carrots
fried   potatoes
grilled onions
grated  carrot

user@bible:~ > awk /carrot/ foods
boiled  carrots
grated  carrot
在此,awk 只选择匹配 carrot 的行

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


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


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

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

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

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

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


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



摘自:《SUSE Linux 10 宝典》人民邮电出版社