0

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 ?

munin24
  • 31
  • 1
  • 6

3 Answers3

1
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

  • The last statement is (entered and displays) properly yet if you (copy and paste) the text it is missing a space prior to the + sign, probably due to a bug in the blog software. –  Nov 03 '14 at 19:53
0

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

4rlekin
  • 748
  • 5
  • 16
0
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)
NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43