getline函数仅仅读取下一条数据,不会影响后续的awk指令的执行。
next不仅读取下一行数据,会导致后续指令不再执行,而是重新读取数据后重新回到awk指令的开始位置,重新匹配重新执行动作指令。
操作实例:
#新建素材
vim test.txt
I have a basketball.
I like air jordan sneakers.
I wanna play and do.
How much the T-shirt?
awk '/air/{getline;print "next line:",$0} {print "other line:",$0}' test.txt
awk '/air/{next;print "next line:",$0} {print "other line:",$0}' test.txt
awk '/I/{next;print "next line:",$0} {print "other line:",$0}' test.txt
awk 'BEGIN{system("ls")}'
awk '{system("echo String:"$0 ">> /tmp/abc.txt")}' test.txt
Tips:
#如果$0不加双引号,结果会是什么?
awk '{system("echo String:$0 > /tmp/abc.txt")}' test.txt
#sqrt平方根函数
awk 'BEGIN{print sqrt(64)}'
#int取整函数
awk 'BEGIN{print int(3.1415926)}'
#rand函数0-1之间的随机函数
awk 'BEGIN{print rand()}'
awk 'BEGIN{print 100*rand()}'
awk 'BEGIN{print int(100*rand())}'
awk 'BEGIN{for(i=1;i<=10;i++)print int(100*rand())}'
#srand函数可以使用expr定义新的随机数种子,没有expr时则使用当前系统时间作为随机数种子。
awk 'BEGIN{srand();print rand()}'
awk 'BEGIN{srand(1234);print rand()}'
awk 'BEGIN{a="Hello World!";print length(a)}'
awk 'BEGIN{a[0]="Hello World!";a[1]="nihao";a[2]="Ciao";print length(a)}'
awk 'BEGIN{a[0]="Hello World!";a[1]="nihao";a[2]="Ciao";print length(a[2])}'
awk '{print length()}' /etc/hosts
awk 'BEGIN{a="Hello World!";print index(a,"e")}'
awk 'BEGIN{a="Hello World!";print index(a,"l")}'
awk 'BEGIN{print index("abcdefg","g")}'
awk 'BEGIN{print match("Abcdefg12345","[A-Z]")}'
awk 'BEGIN{print match("Abcdefg12345","[a-z]")}'
awk 'BEGIN{print match("Abcdefg12345","[0-9]")}'
awk 'BEGIN{print tolower("Abcdefg12345")}'
awk 'BEGIN{print toupper("Abcdefg12345")}'
awk 'BEGIN{a="Nihao";print tolower(a)}'
awk 'BEGIN{a="Nihao";print toupper(a)}'
awk 'BEGIN{split("I like playing the piano.",a);print a[4],a[5],a[3],a[2],a[1]}'
awk 'BEGIN{split("I like playing the piano.",a);print a[4]}'
awk 'BEGIN{split("I:like:playing:the:piano.",a,":");print a[1]}'
awk 'BEGIN{split("I1like2playing3football4.",a,"[0-9]");print a[1],a[2]}'
-gsub(r,s,[t])函数默认可以将字符串t中所有正则表达式r匹配字符串全部替换为s,如果没有指定字符串默认为$0进行替换操作。
awk 'BEGIN{a="This is a good instance";gsub("o","O",a);print a}'
cat /etc/passwd |grep ^root |awk '{gsub("[0-9]","##");print $0}'
awk 'BEGIN{a="This is a good instance";sub("o","O",a);print a}'
cat /etc/passwd |grep ^root |awk '{sub("[0-9]","##");print $0}'
awk 'BEGIN{a="I like learning Shell script.";print substr(a,6)}'
awk 'BEGIN{a="I like learning Shell script.";print substr(a,6,13)}'
function 函数名(参数列表) {命令序列}
-操作实例
awk 'function my() { print "This is a CentOS7."} BEGIN{ my() }'
awk ' \
function max(a,b) { \
if(a>b) {print a} \
else {print b} } \
BEGIN {max(1,2)}'