AWK - 如何用gsub改进这个例子?

时间:2012-05-27 15:08:49

标签: awk gsub

我有一个文件:

one one one
one one
one one
one
one
one

此命令替换了5次“one”,“3”

$ awk '{for(i=1; NF>=i; i++)if($i~/one/)a++}{if(a<=5) gsub("one", "three"); print }' file

three three three
three three
one one
one
one
one

现在同样的事情,但是6次:

$ awk '{for(i=1; NF>=i; i++)if($i~/one/)a++}{if(a<=6) gsub("one", "three"); print }' file

three three three
three three
one one
one
one
one

如何改进上面的例子?我想要这个结果:

three three three
three three
three one
one
one
one

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

awk '{for (i=1; i<=NF; i++) {if ($i ~ /one/) {a++; if(a <= 6) sub("one", "three", $i)}}; print}'