5

I know the sed syntax to add a line after another line in a file, which is

sed -i '/LINE1/a LINE2' FILE

This adds LINE2 after LINE1 in FILE correct? How do I add a line with a backslash at the end? For example, from

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

To

This is a a line \
    Indented line1 \
    Indented line2 \
    Added line \
    Line3
Chris F
  • 14,337
  • 30
  • 94
  • 192

4 Answers4

6

Just put the backslash in and escape it:

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

If you want the four-space indent, then:

sed -i '/line2/a \    Added line \\' FILE
lurker
  • 56,987
  • 9
  • 69
  • 103
2

Just use awk, sed is best for simple substitutions on a single line not for anything involving multiple lines or anything else remotely complicated:

$ 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 will line up your added line with the indenting of the preceding one no matter what your leading white space is because it simply replaces anything after the white space with your replacement text.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • I am trying your solution but it seems not to work : here the link : https://stackoverflow.com/questions/44556152/sed-insert-line-after-match-with-a-double-tab-for-the-beginning-of-inserted-li , if you could see what's wrong, regards –  Jun 15 '17 at 08:19
  • [My answer to your question](https://stackoverflow.com/a/44556217/1745001) specifically shows you how to do exactly what you want and why are you commenting under this answer instead of that one?? – Ed Morton Jun 15 '17 at 13:18
1

You can use the insert command:

sed '/\\$/!i \    Added line \\' file
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
0

does this work for you?

awk 'NR==3{$0=$0 "\n\tAdded Line \\"}7' file
Kent
  • 189,393
  • 32
  • 233
  • 301