ppone
ppone

Reputation: 591

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

Upvotes: 2

Views: 2804

Answers (1)

Dimitre Radoulov
Dimitre Radoulov

Reputation: 28000

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

Upvotes: 3

Related Questions