0

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
0

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

Another awk variant:

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

Some text bar1
Some text bar1, another text bar2

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.