AWK工具学习(一)-awk介绍

misszc 2013-02-20

任何awk语句都由模式和动作组成,模式驱动动作触发事件,动作执行对输入行的处理

awk支持'?'、'+'两个扩展元字符,而grep和sed并不支持

A.1举个小例子,演示awk的使用(以下是全部的操作过程)

[lidc@hd66 awk-experiment]$ touch input
[lidc@hd66 awk-experiment]$ awk '/^$/{print "this is a blank line"}' input
[lidc@hd66 awk-experiment]$ cat input 
1.[lidc@hd66 awk-experiment]$ echo '' > input 
[lidc@hd66 awk-experiment]$ cat input 

2.[lidc@hd66 awk-experiment]$ awk '/^$/{print "this is a blank line"}' input
this is a blank line
3.[lidc@hd66 awk-experiment]$ echo 'test by tony' >input
[lidc@hd66 awk-experiment]$ cat input 
test by tony
4.[lidc@hd66 awk-experiment]$ awk '/^$/{print "this is a blank line"}' input
[lidc@hd66 awk-experiment]$

解释:以上是判断输入文件是不是空行的一个例子,1处输入为空,所以执行2后输出'thisisablankline'

3处输入了非空数据,所以在执行4的时候未输出

另外命令行模式下,如果没有指定输入文件将从命令行读取相关文本

[lidc@hd66 awk-experiment]$ awk '/^$/{print "this is a blank line"}' 

this is a blank line

this is a blank line

this is a blank line

A.2awk编程模型

awk程序由一个主输入循环维持,主循环依次读取文件行,程序员只需要对行进行操作,打开文件、关闭文件的操作都由主循环管理

awk还定义了两个特殊的字段:BEGIN和END。BEGIN用于在未读取文件行之前执行。上例子:

[lidc@hd66 awk-experiment]$ awk 'BEGIN{print "joke"} /^$/{print "this is a blank line"}END{print "the end"}' input
joke
this is a blank line
the end
[lidc@hd66 awk-experiment]$ cat input 
test by tony

[lidc@hd66 awk-experiment]$

A.3调用方法

简单说:

1.命令行执行

awk[-F域分隔符]'awk程序段'输入文件

hdfscat/user/ddclick/visitpath-v2_2013-02-18/step_dict/part-*|awk-F~==~'{print$1}'>urls

2.使用-f调用

awk-fawk脚本文件输入文件

3.设置脚本为可执行,然后直接执行

./awk脚本文件输入文件

相关推荐