1、sub替换函数
[[email protected] shell]$ cat awkfile
a b c d
b d l o
j a b v l i w
w v l w e r v l
a w v e a f a w
[[email protected] shell]$
[[email protected] shell]$ awk ‘{sub("a","A",$0);print $0}‘ awkfile
A b c d
b d l o
j A b v l i w
w v l w e r v l
A w v e a f a w
[[email protected] shell]$
[[email protected] shell]$ awk ‘{sub("a","A");print $0}‘ awkfile
A b c d
b d l o
j A b v l i w
w v l w e r v l
A w v e a f a w
[[email protected] shell]$
[[email protected] shell]$ awk ‘{sub(/a/,"A");print $0}‘ awkfile A b c d
b d l o
j A b v l i w
w v l w e r v l
A w v e a f a w
[[email protected] shell]$
[[email protected] shell]$ awk ‘{sub(/^a/,"A");print $0}‘ awkfile
A b c d
b d l o
j a b v l i w
w v l w e r v l
A w v e a f a w
[[email protected] shell]$
默认替换第一列匹配到的字符串
语法是:sub(替换前的内容(可以使用正则表达式),替换后的内容,替换范围)
下面来替换第五列的字符串
[[email protected] shell]$ awk ‘{sub("a","A",$5);print $0}‘ awkfile
a b c d
b d l o
j a b v l i w
w v l w e r v l
a w v e A f a w
[[email protected] shell]$
2、gsub替换函数
[[email protected] shell]$ awk ‘{gsub("a","A",$0);print $0}‘ awkfile
A b c d
b d l o
j A b v l i w
w v l w e r v l
A w v e A f A w
[[email protected] shell]$
[[email protected] shell]$ awk ‘{gsub("a","A",$1);print $0}‘ awkfile
A b c d
b d l o
j a b v l i w
w v l w e r v l
A w v e a f a w
[[email protected] shell]$
[[email protected] shell]$ awk ‘{gsub(/a/,"A",$1);print $0}‘ awkfile
A b c d
b d l o
j a b v l i w
w v l w e r v l
A w v e a f a w
[[email protected] shell]$
[[email protected] shell]$ awk ‘{gsub(/^a/,"A");print $0}‘ awkfile
A b c d
b d l o
j a b v l i w
w v l w e r v l
A w v e a f a w
[[email protected] shell]$
看到它们之间的区别没有?
sub是局部替换,也就是替换一行之中第一个匹配到的字符串
gsub是全局替换,所有匹配到的字符串都会替换
下面来点好玩的。
[[email protected] shell]$
[[email protected] shell]$ awk ‘{sub($1,"A");print $0}‘ awkfile
A b c d
A d l o
A a b v l i w
A v l w e r v l
A w v e a f a w
[[email protected] shell]$
这样匹配也是局部的。
[[email protected] shell]$ awk ‘{sub($1,"A",$2);print $0}‘ awkfile
a b c d
b d l o
j a b v l i w
w v l w e r v l
a w v e a f a w
[[email protected] shell]$
这里没有匹配到,因为你选择了在第二列进行替换规则,但是匹配的内容在第一列,这样是匹配不到的,记住喔~~~
[[email protected] shell]$ awk ‘{gsub($1,"A");print $0}‘ awkfile
A b c d
A d l o
A a b v l i w
A v l A e r v l
A w v e A f A w
[[email protected] shell]$ awk ‘{gsub($1,"A",$2);print $0}‘ awkfile
a b c d
b d l o
j a b v l i w
w v l w e r v l
a w v e a f a w
[[email protected] shell]$
当然了,awk还有很多玩法,自己去摸索去吧,我实力也就这点了。