1

我有一个文件:

one one one
one one
one one
one
one
one

此命令替换了 5 次“一”、“三”

$ 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

感谢您的帮助。

4

1 回答 1

3
awk '{for (i=1; i<=NF; i++) {if ($i ~ /one/) {a++; if(a <= 6) sub("one", "three", $i)}}; print}'
于 2012-05-27T15:22:27.227 回答