2

How can I append text below the specific number of lines in sed?

More specifically, if I have following 'Target' file,

$ cat Target
##########
# (1)
##########

echo $PWD


##########
# (2)
##########


##########
# (3)
##########

How can I insert a line between '# (2)' block and '# (3)' block? In other world, I want to create 'Goal' file like this by using sed.

$ cat Goal
##########
# (1)
##########

echo $PWD


##########
# (2)
##########

echo "yay"

##########
# (3)
##########

I tried various ways and googled a lot, I cannot find any clue. (Why special pattern '\n' does not work?)

Please give me an advice.

lymose
  • 71
  • 4
  • 1
    This is significantly easier to accomplish with programming language like awk, perl, etc. If you can use that sort of solution, add only 1 tag to indicate which language you would like to use. (You'll get yelled at for having more than 1 language ;-). Good luck. – shellter Aug 05 '11 at 14:35
  • This question about newlines in sed might help - http://stackoverflow.com/questions/1251999/sed-how-can-i-replace-a-newline-n – arunkumar Aug 05 '11 at 14:41

2 Answers2

1
sed '/# (2)/ {n;n;a\
echo "yay"
}' Target > Goal
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
1

This might work for you:

sed '/^# (2)/,/# (3)/{H;//{x;s/.*#\n\n/&echo "yay"\n/p};d}' Target > Goal
##########
# (1)
##########

echo $PWD


##########
# (2)
##########

echo "yay"

##########
# (3)
##########
potong
  • 55,640
  • 6
  • 51
  • 83