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 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 to share