awk是一款强大的对文件内容进行处理的软件,可以当作是一个脚本语言。
这里列出大概的学习框架和简单例子。
【学习列表】
1.Built-in functions for numeric operations
2.Built-in functions for String operations
3.Build-in functions for input output operations
4.awk if statement(if,if else,if else if,:?)
5.awk loops(do while,for loop,break,continue,exit)
6.Build-in variables(FS,OFS,RS,ORS,NR,NF,FILENAME,FNR)
【简单例子】
1. number operations
int log sqrt exp sin cos atan2 rand srand ...
$cat rand.awk BEGIN { while(i<1000) { n = int(rand()*100); rnd[n]++; i++; } for(i=0;i<=100;i++) { print i,"Occured", rnd[i], "times"; } } $
2. string operations
index length match split sprintf sub gsub gensub substr tolower toupper
[root@pandaVM script]# awk 'BEGIN{str="daabaaa" ;sub(/a/,"c&c",str) ;print str}' dcacabaaa
3. input output operations
close fflush system
[root@pandaVM script]# awk 'BEGIN{print date}' [root@pandaVM script]# awk 'BEGIN{system("date")}' Tue Oct 21 10:40:16 CST 2014
4. if statement
$ awk '{ if ($3 >=35 && $4 >= 35 && $5 >= 35) print $0,"=>","Pass"; else print $0,"=>","Fail"; }' student-marks Jones 2143 78 84 77 => Pass Gondrol 2321 56 58 45 => Pass RinRao 2122 38 37 => Fail Edwin 2537 87 97 95 => Pass Dayan 2415 30 47 => Fail
5. for loop ,break continue
$ awk 'BEGIN{ count=1; do print "This gets printed at least once"; while(count!=1) }' This gets printed at least once
6. build-in variables
FS - Input field separator variable.
OFS - Output Field Separator Variable
RS - Record Separator variable
ORS - Output Record Separator Variable
NR - Number of Records Variable
NF - Number of Fields in a record
FILENAME - Name of the current input file
FNR - Number of Records relative to the current input file
$ awk -F':' 'BEGIN{OFS="=";} {print $3,$4;}' /etc/passwd 41=41 100=101 101=102 103=7 105=111 110=116 111=117 112=119
【参考链接】
http://www.thegeekstuff.com/tag/awk-tutorial-examples/
http://www.math.utah.edu/docs/info/gawk_13.html