Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add line with spaces at beginning, and with backslash at end with sed?

Tags:

bash

sed

awk

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
like image 860
Chris F Avatar asked Sep 11 '14 14:09

Chris F


3 Answers

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
like image 138
lurker Avatar answered Oct 13 '22 08:10

lurker


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.

like image 25
Ed Morton Avatar answered Oct 13 '22 07:10

Ed Morton


You can use the insert command:

sed '/\\$/!i \    Added line \\' file
like image 36
Casimir et Hippolyte Avatar answered Oct 13 '22 08:10

Casimir et Hippolyte