How do I add a line with leading spaces and a backslash at the end with sed?

I know the sed syntax for adding a line after another line in a file, which is

sed -i '/LINE1/a LINE2' FILE

      

Does it add LINE2 after correctly setting LINE1 to FILE? How do I add a backslash line at the end? For example from

This is a a line \
    Indented line1 \
    Indented line2 \
    Line3

      

For

This is a a line \
    Indented line1 \
    Indented line2 \
    Added line \
    Line3

      

+3


source to share


4 answers


Just insert the backslash and strip it out:

sed -i '/line2/a Added line \\' FILE

      



If you want an indentation with four spaces, then:

sed -i '/line2/a \    Added line \\' FILE

      

+5


source


You can use the insert command:



sed '/\\$/!i \    Added line \\' file

      

+1


source


Just use awk, sed is best for simple one-line substitutions, not for anything multi-line or anything else remotely complex:

$ awk '{print} /line2/{ print substr($0,1,match($0,/[^[:space:]]/)-1) "Added line \\" }' file
This is a a line \
    Indented line1 \
    Indented line2 \
    Added line \
    Line3

      

The above line will align your added line with the indented previous one, no matter what your leading white space means, because it just replaces anything after the space with your replacement text.

+1


source


does it work for you?

awk 'NR==3{$0=$0 "\n\tAdded Line \\"}7' file

      

0


source







All Articles