munin24
munin24

Reputation: 31

SED insert new line after pattern

I have scripts containing the following line:

   echo  + /etc>>$BUFFER

I would like to edit them with sed and insert another line right after this:

   echo  + /etc>>$BUFFER
   echo  - /etc/cache>>$BUFFER

and leave the rest of the file as it was. What is the SED regexp to do this ?

Upvotes: 0

Views: 1105

Answers (3)

user3897784
user3897784

Reputation:

sed -i  '$a echo  - /etc/cache>>$BUFFER' myfile.txt

The $ says the last line and a is append the -i option writes the file in place.

If you want the match anywhere you can address it with a regex / / like this just make sure to escape the / like / since sed expects the regex to be encapsulated in / /

sed -i '/echo + \/etc>>$BUFFER/a echo - /etc/cache>>$BUFFER' myfile.txt

Since the (copy & paste) of the above statement omits a space prior to the first + sign (likely due to a BUG in the software that runs the posts to this website) - here is version that should work when copied ):

sed -i '/echo \ + \/etc>>$BUFFER/a echo - /etc/cache>>$BUFFER' myfile.txt

or if you want to avoid escaping the single front slash in the future (not really useful in this case since its only one but if you had a lot of front slashes - again weird escaped space is only due to a BUG in the software of this website (or my browser firefox) if you type it on the command line you can put the spacing double yourself as it appears in the askers question) :

sed -i '\@echo \ + /etc>>$BUFFER@a echo - /etc/cache>>$BUFFER' myfile.txt

Upvotes: 1

4rlekin
4rlekin

Reputation: 758

If i understood you correctly this should work:

sed 's/echo \+ .*etc>>\$BUFFER/echo + \/etc>>\$BUFFER\necho - \/etc\/cache>>\$BUFFER/'

It isn't maybe best solution (im not sure how to deal with forward slash in pattern - theorethically it should be enough to escape it like: \/ but strangely it isn't working)
This should work though

Upvotes: 0

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed -i '\#^ *echo  + /etc>>\$BUFFER *$# a\
echo  - /etc/cache>>$BUFFER' YourFile
  • It will add the line after EACH occurence of echo + /etc>>$BUFFER.
  • I just add the line delimiter to limit to only this exact line content (but could have heading or trailing space)

Upvotes: 0

Related Questions