awk提供了很多的函数提供给我们使用,现在简单的介绍几个内置函数。
1、split
split函数是用来将一个字符串进行划分为数组的函数:
split(“string”,”arrar_name”,”separator”)
其中第一个参数为划分的字符串或者是变量,即我们想把那个变量变为数组,第二个参数就是我们想进行划分的数组的名字是什么,这个根据自己的需求进行定义,最后就是在划分的过程中的分隔符,这个分隔符指的是第一个参数的分隔符。
awk 'BEGIN{n=split("hello",a,"");for(i=1;i<=n;i++)print a[i]}'
h
e
l
l
o
需要注意的是,首先在中间的参数是数组的名字,这个是不需要有引号的,否则报错,另外n=split("hello",a,""),这样n就是数组的长度,并且数组的下标是从1开始的。
2、gsub
gsub(“被替换字符串的正则匹配模式”,”用什么字符创进行替换”,”被替换的字符串”)
cat file
hello world hello nginx hello php
hello shell apple banana
hello awk
hi world
下面将文本中的hello全部替换为linux
awk '{printf gsub("hello","linux");print " "$0}' file
3 linux world linux nginx linux php
1 linux shell apple banana
1 linux awk
0 hi world
解析:gsub返回的是被替换的字符串的个数,第一行原来有三个hello,所以输出的是3,最后将替换后的记录进行输出,此外,在gsub函数中,需要提供的是三个变量,如果第三个变量不写的话,那么第三个参数默认的为$0,另外sub函数和gsub函数的原理是一样的,只不过是sub这是替换本条记录第一次出现的目标字符串,再有就是被替换字符串的为止可以也可以是一个正则表达式,也可以是一个指定的字符串。
3、substr
substr(“源字符串”,”开始截取的为止”,”截取的长度”)
echo "hello world" | awk '{s1=substr($0,2,1);print s1}'
e
这时候会输出e,上面的解释为从$0截取,第二个字符开始,截取的长度是1,所以就是字符e了。
4、match
match(“字符串”,”查找的正则或者是字符串”)
cat file
hello world hello nginx hello php
hello shell apple banana
hello awk
hi world
awk '{print match($0,"hello")}' file
1
1
1
0
awk '{print match($0,"nginx")}' file
19
0
0
0
分别匹配nginx 和hello在文本中出现的为止。
5、index
index(s,r)返回子串r在s中的位置,如果r不存在s中,那么返回值为0。
6、tolower(s):将字符串s转化为小写,toupper(s):将字符串s转化为大写。
7、gensub
gensub(“想要进行替换的字符串或者正则”,”替换的字符串”,替换第几个)
cat file
hello world hello nginx hello php
hello shell apple banana
hello awk
hi world
awk '{print gensub("hello","linux",1)}' file
linux world hello nginx hello php
linux shell apple banana
linux awk
hi world
将记录中第一次出现的hello用linux替换掉。
需要注意的是,gensub是不会改变原来的target的,什么意思呢,sub和gsub会替换原来的target。也就是说,进行gensub之后,如果print $0之后,输出的还是原来的内容,这叫做target没有改变,但是如果利用的是gsub或者是sub函数,那么输出$0就是经过awk处理的$0了。