Reputation: 51
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:
x1 this is some content.
This is x2 some more content x3. x4
This is yet x5 some more [x6] content.
How can I replace all of the matches with an incrementing number and with a string prefix?
my quetion is very similar to How to replace all matches with an incrementing number in BASH? however the solution given which i tried to modify, can't seem to get working.
awk '{for(x=1;x<=NF;x++)if($x~/AAAAAA/){sub(/AAAAAA/,"x"++i)}}1' file
thanks.
Upvotes: 2
Views: 703
Reputation: 67567
another awk
$ awk -v w='AAAAAA' '{while($0~w) sub(w,"x"++c)}1' file
x1 this is some content.
This is x2 some more content x3. x4
This is yet x5 some more [x6] content.
essentially an inefficient gsub
.
this one uses record separator as the search word
$ awk -v RS='AAAAAA' -v ORS='' 'NR>1 && $0="x"++c $0' file
x1 this is some content.
This is x2 some more content x3. x4
This is yet x5 some more [x6] content.
to suppress the last one is harder, instead delayed the replacement by one and suppress the first one.
Upvotes: 4
Reputation: 92904
The shortest perl
trick:
perl -pe 's/\bA+\b/x.++$i/ge' file
The output:
x1 this is some content.
This is x2 some more content x3. x4
This is yet x5 some more [x6] content.
Upvotes: 0
Reputation: 133780
awk
to save here:
awk '{for(i=1;i<=NF;i++){if($i~/A+/){val="x"++count;sub(/A+/,val,$i)}}} 1' Input_file
OR
awk '{for(i=1;i<=NF;i++){if($i~/A+/){sub(/A+/,"x"++count,$i)}}} 1' Input_file
Output will be as follows.
x1 this is some content.
This is x2 some more content x3. x4
This is yet x5 some more [x6] content.
Upvotes: 1