awk learn note

 avatar
movit
markdown
3 years ago
3.6 kB
10
Indexable

awk

awk基础语法

awk程序结构

  •   BEGIN {awk-command}
      BEGIN区域(可选项)
      body命令执行前执行BEGIN区域,仅执行一次,打印报文头或初始化变量
      可以用一个或多个awk-command
    
  •   /pattern/{awk-command}
      body区域,输入文本处理命令
    
  •   END {awk-command}
      END区域(可选项)
      body命令执行后执行END区域,仅执行一次,打印报头尾,结果
    
  • awk 'BEGIN {awk-command} /pattern/{awk-command} END {awk-command}' input-file

命令行

  • awk -Fs '/pattern/{action}' input-file
  • awk -Fs '{action}' input-file
  •   分界符可以直接以-Fs或-F"s"形式指定
    

awk脚本

  •   awk -Fs -f script.awk input-file
    

内置变量

FS

  •   FS:field separator,字段分隔符
      默认字段分隔符为空格,awk命令行通过-F指定
      FS只能在BEGIN区域使用
    

OFS

  •   OFS:output field separator,输出字段分隔符
      默认为空格,可以在BEGIN区域指定,BEGIN {OFS="s"}
    

RS

  •   RS:record separator(row separator),记录分隔符(行分隔符)
      默认值为换行符,可以理解为行与行之间的分隔符
    

ORS

  •   ORS:output record separator(output row separator),记录分隔符(行分隔符)
      默认值为换行符,可以理解为行与行之间的分隔符
    

NR

  •   NR:number of record(number of row),记录序号(行号)
    

FNR

  •   FNR:file number of record(file number of row),当前文件行数
      awk处理多个文件时,awk NR会从上一个文件的行数继续计数,FNR记录当前文件真实的行数
    

FILENAME

  •   FILENAME:当前处理的文件名
      从标准输入获取,FILENAME为-
    

自定义变量及操作符

变量

  • 字符开头,后续数字字母下划线

一元操作符

  • -,+,++,--

算数操作符

  • +,-,*,/,%

字符串拼接

  • string3=string2 string1

赋值操作符

  • =,+=,-=,*=,/=,%=

比较操作符

  • ,>=,<,<=,==,!=,&&,||

正则表达式

  • ~匹配,!~不匹配

条件和循环

if语句

  • if(){ command; }elseif(){ command; } else{ command }

?:语句

  • true? true_A:false_B;

while语句

  • while(true){ commands; }

do while

  • do{ command } while();

for loop

  • for(initial;condition;inc/dec){ command; }

break

  • 跳出循环体

continue

  • 跳出当前循环命令

awk关联数组

定义数组

  • 创建并复制:array[index]=value
  • 删除数组:delete array[index]

引用数组

  • var=array[index]
  • print array[index]
  • for(index in array-name):数组中是否存在索引值

多维数组

  • BEGIN { item["1,1"]=10; item["1,2"]=20; item[2,1]=30; item[2,2]=40; for(x in item) print "Index",x,"contains",item[x]; } result: Index 1,2 contains 20 Index 21 contains 30 Index 22 contains 40 Index 1,1 contains 10
  • 1,1 1,2因为用双引号所以被当作一维数组
  • 2,1 2,2是多为数组,下表使用SUBSEP默认值034作为分隔符 (不可打印)

下标分隔符SUBSEP

  • 默认值为不可打印字符034
  • 指定SUBSEP="string"
  • BEGIN {
    SUBSEP=":"
    item["1,1"]=10;
    item["1,2"]=20;
    item[2,1]=30;
    item[2,2]=40;
    for(x in item)
    print "Index",x,"contains",item[x];
    }
    result:
    Index 1,2 contains 20
    Index 2:1 contains 30
    Index 2:2 contains 40
    Index 1,1 contains 10