码迷,mamicode.com
首页 > 其他好文 > 详细

awk命令的小记1

时间:2017-06-29 01:09:15      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:logs   匹配   enter   arc   执行   表达式   inf   str   shel   

awk命令的基本功能:以行为单位进行搜索,并对匹配的行进行对应的处理。

基本格式:awk ‘pattern {actions}’  file

patterns和actions可以缺少一个,但不能两个都缺,缺patterns时,是对所有行执行actions;缺actions,是对符合行进行打印命令。

pattern:

1./正则表达式/

2.表达式:匹配表达式不为o或null的行。$awk "$1==‘li‘" file :打印第一个字符是“li”的行。

3.beginpattern-endpattern模式:分为两个表达式,以逗号隔开,开始行是匹配第一个表达式,结束行匹配第二个表达式。

$awk ‘$1=="first",$1=="last"‘ file :打印多行,第一行是第一个字符为first的行,最后一行是第一个字符为last的行。

4.BEGIN-END: 格式:BEGIN{actions}  pattern {actions}  END{actions}

5.BEGINFILE-ENDFILE:

shell脚本中常用变量作为awk的pattern的一部分,有两种使用方式:

1.直接使用变量:(使用双引号将变量实现)

1 printf "Enter search pattern: "
2 read pattern
3 awk "/$pattern/ "‘{ nmatches++ }
4      END { print nmatches, "found" } /path/to/data

2.将shell变量的值赋给awk变量:

1 printf "Enter search pattern: "
2 read pattern
3 awk -v pat="$pattern" $0 ~ pat { nmatches++ }
4        END { print nmatches, "found" } /path/to/data

 

acitions:由一个或多个awk语句组成,由{}包裹着,每个语句间由分号间隔或隔行间隔。

/foo/  { }     match foo, do nothing — empty action
/foo/          match foo, print the record — omitted action

awk支持的语句包括:

表达式语句

控制语句:if语句,while语句,do-while语句,for语句,swith语句,break语句,continue语句。。。

输出语句

 

awk命令的小记1

标签:logs   匹配   enter   arc   执行   表达式   inf   str   shel   

原文地址:http://www.cnblogs.com/timeisbiggestboss/p/7062254.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!