0

I want to use sed command to append text at multiple occurrence of string.

For Ex:

Hello world
types="program"
Mario
types="Game"
Hello world
types="program"
Mario
types="Game"

So at first occurrence of Mario i want to append 'firstMario' and at next occurrence 'secondMario', and so on. OutPut:

Hello world
types="program"
firstMario
types="Game"
Hello world
types="program"
secondMario
types="Game"

2 Answers 2

2
sed '
  /Mario/{
    s//first&/
    :1
      n
      s//second&/
    b1
  }'

Or:

sed '
  1 {
    x;s/^/first/;x
  }
  /Mario/ {
    G
    s/\(Mario.*\)\n\(.*\)/\2\1/
    x;s/second/third/;s/first/second/;x
  }'

Though to allow more than one Mario per line and generalize to more substitutions, I'd use perl instead:

perl -pe 'BEGIN{@words=qw(first second third)}
          s/(?=Mario)/$words[$n++]/ge'
1
  • With unknown input (unknown no. of occurrences) one could use perl module Lingua::EN::Numbers Commented Aug 14, 2015 at 17:24
0

You will have a hard time using "first second third ..." in an automated way, since they are not described anywhere (at least there is no standard tool). I'll give a solution with integers:

n=$( grep -c '^Mario$' file )
for (( i=1 ; i<=$n ; i++ )) ; do
  sed -i "1,/^Mario$/s/^Mario$/$i&/" file
done

output:

Hello world
types="program"
1Mario
types="Game"
Hello world
types="program"
2Mario
types="Game"

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.