Using sed, Insert a line above or below the pattern?

ScriptingSedAwk

Scripting Problem Overview


I need to edit a good number of files, by inserting a line or multiple lines either right below a unique pattern or above it. Please advise on how to do that using sed, awk, perl (or anything else) in a shell. Thanks! Example:

some text
lorem ipsum dolor sit amet
more text

I want to insert consectetur adipiscing elit after lorem ipsum dolor sit amet, so the output file will look like:

some text
lorem ipsum dolor sit amet
consectetur adipiscing elit
more text

Scripting Solutions


Solution 1 - Scripting

To append after the pattern: (-i is for in place replace). line1 and line2 are the lines you want to append(or prepend)

sed -i '/pattern/a \
line1 \
line2' inputfile

Output:

#cat inputfile
 pattern
 line1 line2 

To prepend the lines before:

sed -i '/pattern/i \
line1 \
line2' inputfile

Output:

#cat inputfile
 line1 line2 
 pattern
        

Solution 2 - Scripting

The following adds one line after SearchPattern.

sed -i '/SearchPattern/aNew Text' SomeFile.txt

It inserts New Text one line below each line that contains SearchPattern.

To add two lines, you can use a \ and enter a newline while typing New Text.

POSIX sed requires a \ and a newline after the a sed function. [1] Specifying the text to append without the newline is a GNU sed extension (as documented in the sed info page), so its usage is not as portable.

[1] https://unix.stackexchange.com/questions/52131/sed-on-osx-insert-at-a-certain-line/

Solution 3 - Scripting

Insert a new verse after the given verse in your stanza:

sed -i '/^lorem ipsum dolor sit amet$/ s:$:\nconsectetur adipiscing elit:' FILE

Solution 4 - Scripting

More portable to use ed; some systems don't support \n in sed

printf "/^lorem ipsum dolor sit amet/a\nconsectetur adipiscing elit\n.\nw\nq\n" |\
    /bin/ed $filename

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvehomzzzView Question on Stackoverflow
Solution 1 - ScriptingKamalView Answer on Stackoverflow
Solution 2 - ScriptingjahroyView Answer on Stackoverflow
Solution 3 - ScriptingalinsoarView Answer on Stackoverflow
Solution 4 - ScriptingChris ReesView Answer on Stackoverflow