awk(一)

http://www.ibm.com/developerworks/cn/linux/shell/awk/awk-1/ 
1,什么是awk? awk如何工作?
awk 适合于文本处理和报表生成,它还有许多精心设计的特性,允许进行多种方式的编程。

第一个 Awk

您应该会看到 /ect/passwd 文件中的内容,本文使用该文件来解释 awk 的工作原理。当调用 awk 时,我们指定 /etc/passwd 作为输入文件。Awk 在执行期间对 /etc/passwd 文件中的每一行依次执行 print 命令。所有输出都发送到 stdout,可以得到类似 cat 命令的结果。

现在解释代码块 { print }。在 Awk 中,花括号用于将代码分块,这与 C 语言类似。我们的代码块中只有一条 print 命令。在 Awk 中,当 print 命令单独出现时,将打印当前行的全部内容。

$ awk '{ print $0 }' /etc/passwd

在 Awk 中,变量 $0 表示整个当前行,因此 printprint $0 的作用完全相同。

$ awk '{ print "" }' /etc/passwd

$ awk '{ print "hiya" }' /etc/passwd

运行该脚本,屏幕上讲显示多行 hiya。:)



多个字段

print $1
$ awk -F":" '{ print $1 $3 }' /etc/passwd

halt7
operator11
root0
shutdown6
sync5
bin1
....etc.

print $1 $3
$ awk -F":" '{ print $1 " " $3 }' /etc/passwd

$1 $3
$ awk -F":" '{ print "username: " $1 "/t/tuid:" $3 }' /etc/passwd

username: halt          uid:7
username: operator uid:11
username: root uid:0
username: shutdown uid:6
username: sync uid:5
username: bin uid:1


....etc.

你可能感兴趣的:(编程,c,工作,脚本,语言,报表)