Mohammedz.com

For Linux and Shell scripting.


13 Comments

SED: change/insert/append lines after matching a pattern

Do you want to change/insert/append lines after matching a pattern from a file? If yes, you can use sed to do that.

—————————–
I’m pasting the relevant parts from sed manpage followed by some examples.
a \
text – Append text, which has each embedded newline preceded by a backslash.

i \
text – Insert text, which has each embedded newline preceded by a backslash.

c \
text – Replace the selected lines with text, which has each embedded newline preceded by a backslash.
—————————–

Here is an example to show you the usage. You can either use it from command line or from within shell scripts.

Description of the example: The filename.txt contains 3 lines as shown below and I’m gonna do all manipulations by matching the pattern “second line”.

# cat > filename.txt
first line
second line
third line
#

Match “second line” pattern and append “append line” into the matched address.
# sed ‘/second line/a\
append line
‘ filename.txt

Output of the above command:
first line
second line
append line
third line

Match “second line” pattern and insert “insert line” to the matched address.
# sed ‘/second line/i\
insert line
‘ filename.txt

Output of the above command:
first line
insert line
second line
third line

Match “second line” pattern and change that line with “change line”.
# sed ‘/second line/c\
change line
‘ filename.txt

Output of the above command:
first line
change line
third line

Hope this helps 🙂

~mohammed