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
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'
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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.