Wujo
Wujo

Reputation: 1867

How to replace occurence of substring with another string containing index of occurence?

I need to do what's described below, in bash script.

Let's say I have a file containing text:

Some text foo
Some text foo, another text foo

I want to replace foo with another string but ended with the index of foo in the line

So I want the output to be:

Some text bar1
Some text bar1, another text bar2

Upvotes: 0

Views: 57

Answers (3)

oguz ismail
oguz ismail

Reputation: 50805

Something like this should do that:

awk '{ for (i = 1; sub(/foo/, "bar" i); i++) ; } 1' file

Note that foo is interpreted as a regular expression.

Upvotes: 2

Shawn
Shawn

Reputation: 52614

Using a perl one-liner:

$ perl -pe 'my $i = 1; s/foo/"bar" . $i++/eg' input.txt
Some text bar1
Some text bar1, another text bar2

Upvotes: 2

anubhava
anubhava

Reputation: 786271

Another awk variant:

awk '{for(i=0; sub(/foo/, "bar" ++i););} 1' file

Some text bar1
Some text bar1, another text bar2

Upvotes: 0

Related Questions