echo "11111"| awk 'BEGIN{FS=OFS=""}{$4="x";print}'
111x1
echo "11111"| awk '{print $0=gensub("1","x",4)}'
111x1
echo "11111"| awk '{print $0=gensub("1","x","g")}'
xxxxx
[解析]
阁下是不是豁然开朗了很多?这就是gensub的便捷,在这里面不再需要字段分割符,用数字即可指定你要替换的某一位。g和G是指全局替换,要双引号标记起来。特别注意的是gensub是不会修改原记录的,所以要对$0进行一个赋值。“themodified string is returned as the result of the function and theoriginal target string is not changed”。接下来我们再看看一个更复杂的运用。
echo "unix linux"| awk '{print gensub(/(.+)(.+)/,"\\2\\1","g")}'
linux unix
echo "xaax xbx xxx:xaax xbxxxx"| awk -F:-vOFS=":"'{$2=gensub(/x([^x]+)x/,"\\1YY",2,$2)}1'
xaax xbx xxx:xaax bYYxxx