Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all matches with an incrementing number in BASH?

Tags:

bash

sed

I have a text file like this:

AAAAAA this is some content.
This is AAAAAA some more content AAAAAA. AAAAAA
This is yet AAAAAA some more [AAAAAA] content.

I need to replace all occurrence of AAAAAA with an incremented number, e.g., the output would look like this:

1 this is some content.
This is 2 some more content 3. 4
This is yet 5 some more [6] content.

How can I replace all of the matches with an incrementing number?

like image 366
Village Avatar asked May 10 '14 05:05

Village


1 Answers

Here is one way of doing it:

$ awk '{for(x=1;x<=NF;x++)if($x~/AAAAAA/){sub(/AAAAAA/,++i)}}1' file
1 this is some content.
This is 2 some more content 3. 4
This is yet 5 some more [6] content.
like image 141
jaypal singh Avatar answered Sep 30 '22 18:09

jaypal singh