awk notes

awk语法

awk 'pattern + { action}'

说明: (1) 单引号’‘是为了与shell命令区分开来
(2) 大括号{}表示一个命令分组
(3) pattern表示一个过滤器, 命中了pattern的行才进行action处理
(4) action是处理动作
(5) 用#作为注释

pattern说明

显示hello.txt的第三行到第5行

cat hello.txt | awk 'NR==3, NR=5 { print $0; }'

显示包含hello的行

cat hello.txt | awk '/hello/'

显示长度大于3的行

cat hello.txt | awk 'length($0) > 3 { print NR, "--", $0 }'

内置变量

  1. FS – field seperator 默认是空格, 可以通过-F指定
  2. NR – 当前行号, 从1开始
  3. NF – number of field
    4 $0 – 当前行的内容
    5 $n – 当前行的第几条记录

内置函数

  1. gsub(r, s)
  2. index(s, t)
  3. length(s)
  4. match(s,r)
  5. split(s,a,fs)
  6. substr(s,p)

操作符

  1. 运算类似于C, 支持 +, -, *, /, %, ++, –, +=, -= 等诸多操作
  2. 判断类似于C, 支持 ==, !=, >, =>, ~(匹配于)

控制流程

  1. BEGIN与END, 本质上也是个pattern, BEGIN用于awk程序开始前做些初始化工作, END收尾 比如统计字符个数
awk '
BEGIN {
  count = 0;
}

{
  count += length($0);
}

END {
  print "总字符个数为: ", count;
}
'
  1. 流程控制语句
  2. if(condition){}else{}
  3. while{}
  4. do{}while(condition);
  5. for(init;condition;step){}
  6. break/continue:如果有END,会执行END中的收尾工作
    流程控制语句用法几乎与c相同。

与shell交互

  1. awk中使用shell中定义的变量:使用单引号即可;
#!/bin/bash
STR="hello"
echo | awk '{ print "'${STR}'" }'
  1. awk中使用shell命令:使用双引号,或者system命令
echo hello | awk '{
  print $0 | "cat"
}'

echo | awk '{
  system("date > date.txt")
}'
  1. awk中的变量输出到shell: 没办法, 老实用文件

  2. getline: awk里, 从文件读取变量到awk中

#!/bin/bash
echo | awk '{
  while(getline < "date.txt") {
    print $0;
  } 
}'

Published: July 18 2012