replace nth occurrence of character in a file using awk regardless of the line
I am trying to replace the nth occurrence of a character or string regardless of the 开发者_开发百科line using awk.
So if our data was this
|||||||
||||||
|||||
|||
and we were trying to replace | with A
then the output should look like this, assuming we want to replace every 3rd occurance
||A||A|
|A||A|
|A||A
||A
The current awk command I am using is this
awk '/|/{c++;if(c==3){sub(/|/,"A");c=0}}1' test.data
and it wrongly outputs this
|||||||
||||||
A||||
|||
also the data can look like this
|||xfsafrwe|||asfasdf|
|safasf|||asfasdf||
||asfasf|||
|||
and the result of course is this
||Axfsafrwe||Aasfasdf|
|safasfA||asfasdfA|
|Aasfasf||A
||A
Thanks
With GNU awk:
awk '{
for (i = 0; ++i <= NF;)
++c % n || $i = v
}1' OFS= FS= n=3 v=A infile
Adjusted after OP clarification:
awk '{
for (i = 0; ++i <=NF;)
if ($i == o)
++C % c || $i = n
} 1' FS= OFS= c=3 o=\| n=A infile
精彩评论