Tedee12345
Tedee12345

Reputation: 1210

AWK - how to improve this example with gsub?

I have a file:

one one one
one one
one one
one
one
one

This command replaced 5 times "one", "three"

$ 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

Now the same thing, but 6 times:

$ 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

How to improve the above example? I want this result:

three three three
three three
three one
one
one
one

Thank you for your help.

Upvotes: 1

Views: 1351

Answers (1)

Dennis Williamson
Dennis Williamson

Reputation: 360153

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

Upvotes: 3

Related Questions