awk内置函数gsub

来源:互联网 发布:淘宝卖家怎么设置佣金 编辑:程序博客网 时间:2024/06/06 00:50
awk内置函数gsub
gsub():
gsub(r,s) 在整个$0中用s替代r;gsub(r,s,t) 在整个t中用s替代r
下面举个例子:
file
hello helloworld
hi    hello
how are you
如果想让hello 被hi代替的话,可以利用下面的语句实现
awk ‘{gsub(“hello”,”hi”);print $0}’ file
[root@test1 home]# awk '{ gsub("hello","hi");print $0}' 4 
hi hiworld
hi    hi
how are you
此函数的另外的一个功能就是统计某个字符在一行中出现的次数
awk ‘{print gsub(“hello”,”any character”)}’ file
其中gsub中的两个参数第一个为我们要统计的单词,第二个为任意的一个字符即可。这样就统计出了hello 在每一行中出现的次数。
[root@test1 home]# awk '{print NR,gsub("hello"," ")}' file
1 2
2 1
3 0

0 0