`
阅读更多

sample文件如下, 便于测试:

Heigh-ho! sing, heigh-ho! unto the green holly:
Most friendship is feigning, most loving mere folly:
Then, heigh-ho, the holly!

一. 使用 

1.  显示全部内容:

awk '{ print }'  sample

 解释的过程为如下:

 2. 管道来源:

cat sample | awk '{ print }'

 3. -f参数:

所以,假设一个名为 progfile 的文件中包含下面的内容:

{ print } 

awk -f progfile sample

 上面三个的参数打印的一致.

二. 按照特定的字符进行分割

 

上图为以换行符把Record分割, 在Record内部用空格分割到Filed的逻辑结构. 
1. 使用BEGIN对感叹号 (!) 作为字段分隔符打印示例数据的第 1 个字段:

$ awk ' BEGIN { FS = "!" } { print $1 } ' sample
Heigh-ho
Most friendship is feigning, most loving mere folly:
Then, heigh-ho, the holly
$

2. 使用-F改变分隔符:

#用=分割每行中的两个字符串,并分别打印出来
$vi shell.txt
ruanjianwang=20130101
greatwqs=20130456
eagle=20130202
$ awk -F "=" ' { print $1,$2 } ' shell.txt
ruanjianwang 20130101
greatwqs 20130456
eagle 20130202
$

 

$ awk -F "," ' { print $2 } ' sample
 heigh-ho! unto the green holly:
 most loving mere folly:
 heigh-ho
$
$ awk -F ":" ' { print $5 } ' /etc/passwd
# show user in system

 不能使用-F "!", 特殊字符原因.

 以:分割,第一位用户名,判断用户名为hadoop的行:

$ awk -F ":" '$1 == "hadoop"' /etc/passwd
hadoop:x:501:501::/home/hadoop:/bin/bash
$

大小比较

$ df | awk '$4>1000000 '
Filesystem           1K-blocks      Used Available Use% Mounted on
                       9934940   4960160   4461964  53% /home
tmpfs                  4087664         0   4087664   0% /dev/shm
/dev/sdb1            258027584  11962992 232957564   5% /data
$

 

三. 常见的AWK 变量

 

变量 描述
NF  该变量包含每个记录的字段个数。
NR  该变量包含当前的记录个数。
FS  该变量是字段分隔符。
RS  该变量是记录分隔符。
OFS  该变量是输出字段分隔符(为-F指定的符号,或者2.1中的情形)。
ORS  该变量是输出记录分隔符(一般为换行符)。
FILENAME  该变量包含所读取的输入文件的名称。
IGNORECASE  当 IGNORECASE 设置为非空值,GAWK 将忽略模式匹配中的大小写。 

1. NR测试(这里打印的1,2,3:相当于行号:起始为1):

$ awk '{ print NR, $NR }' sample
1 Heigh-ho!
2 friendship
3 the
$

NR为包含的记录个数,这里用行进行了分割,即上图中的Recode.  $NR 为显示参数,

2. NR和NF测试:

NF为每个Recode中根据字符串拆分后的字段(编号,起始为1)

$ awk ' { print "Record " NR " has " NF " fields and ends with " $NF}' sample
Record 1 has 7 fields and ends with holly:
Record 2 has 8 fields and ends with folly:
Record 3 has 4 fields and ends with holly!

四. 常用的 GAWK 语句

语句 描述
exit 停止程序的执行,并且退出。
next 停止处理当前记录,并且前进到下一条记录。
nextfile 停止处理当前文件,并且前进到下一个文件。
print 打印使用引号括起来的文本、记录、字段和变量。(缺省情况下是打印出当前整行记录。)
printf 打印格式化文本,类似于它的 C 语言对等成分,但必须指定结尾的换行。
sprintf

返回格式化文本字符串,与 printf 使用相同的格式。

很多时候用print

参考:

http://blog.csdn.net/tianlesoftware/article/details/6278273

http://www.ibm.com/developerworks/cn/education/aix/au-gawk/index.html

  • 大小: 6 KB
  • 大小: 15.1 KB
分享到:
评论
1 楼 greatwqs 2013-06-20  
使用AWK统计文本中含有某关键词出现的次数:
统计wqs关键词出现的次数
[hadoop@hadoopclus ~]$ echo 'greatwqsxpwqswqs'|awk -F'wqs' '{print NF-1}'
3

相关推荐

Global site tag (gtag.js) - Google Analytics