标签:linux awk
1、sub替换函数
[xiaomo@Arch-XIAOMO 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
[xiaomo@Arch-XIAOMO shell]$
[xiaomo@Arch-XIAOMO 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
[xiaomo@Arch-XIAOMO shell]$
[xiaomo@Arch-XIAOMO 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
[xiaomo@Arch-XIAOMO shell]$
[xiaomo@Arch-XIAOMO 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
[xiaomo@Arch-XIAOMO shell]$
[xiaomo@Arch-XIAOMO 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
[xiaomo@Arch-XIAOMO shell]$
默认替换第一列匹配到的字符串
语法是:sub(替换前的内容(可以使用正则表达式),替换后的内容,替换范围)
下面来替换第五列的字符串
[xiaomo@Arch-XIAOMO 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
[xiaomo@Arch-XIAOMO shell]$
2、gsub替换函数
[xiaomo@Arch-XIAOMO 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
[xiaomo@Arch-XIAOMO shell]$
[xiaomo@Arch-XIAOMO 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
[xiaomo@Arch-XIAOMO shell]$
[xiaomo@Arch-XIAOMO 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
[xiaomo@Arch-XIAOMO shell]$
[xiaomo@Arch-XIAOMO 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
[xiaomo@Arch-XIAOMO shell]$
看到它们之间的区别没有?
sub是局部替换,也就是替换一行之中第一个匹配到的字符串
gsub是全局替换,所有匹配到的字符串都会替换
下面来点好玩的。
[xiaomo@Arch-XIAOMO shell]$
[xiaomo@Arch-XIAOMO 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
[xiaomo@Arch-XIAOMO shell]$
这样匹配也是局部的。
[xiaomo@Arch-XIAOMO 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
[xiaomo@Arch-XIAOMO shell]$
这里没有匹配到,因为你选择了在第二列进行替换规则,但是匹配的内容在第一列,这样是匹配不到的,记住喔~~~
[xiaomo@Arch-XIAOMO 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
[xiaomo@Arch-XIAOMO 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
[xiaomo@Arch-XIAOMO shell]$
当然了,awk还有很多玩法,自己去摸索去吧,我实力也就这点了。
本文出自 “小莫” 博客,请务必保留此出处http://xiaofengmo.blog.51cto.com/10116365/1751004
标签:linux awk
原文地址:http://xiaofengmo.blog.51cto.com/10116365/1751004