Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert multiple lines of text before specific line using Bash

I am trying to insert a few lines of text before a specific line, but keep getting sed errors when I try to add a new line character. My command looks like:

sed -r -i '/Line to insert after/ i Line one to insert \\
    second new line to insert \\
    third new line to insert' /etc/directory/somefile.txt

The error that is reported is:

sed: -e expression #1, char 77: unterminated `s' command

I've tried, using \n, \\ (as in the example), no character at all, just moving the second line to the next line. I've also tried something like:

sed -r -i -e '/Line to insert after/ i Line one to insert'
    -e 'second new line to insert'
    -e 'third new line to insert' /etc/directory/somefile.txt

EDIT!: Apologies, I wanted the text inserted BEFORE the existing, not after!

like image 238
MeanwhileInHell Avatar asked Aug 14 '15 09:08

MeanwhileInHell


3 Answers

On MacOs I needed a few more things.

  • Double backslash after the i
  • Empty quotes after the -i to specify no backup file
  • Leading backslashes to add leading whitespace
  • Trailing double backslashes to add newlines

This code searches for the first instance of </plugins in pom.xml and inserts another XML object immediately preceding it, separated by a newline character.

sed -i '' "/\<\/plugins/ i \\
\            <plugin>\\
\                <groupId>org.apache.maven.plugins</groupId>\\
\                <artifactId>maven-source-plugin</artifactId>\\
\                <executions>\\
\                    <execution>\\
\                        <id>attach-sources</id>\\
\                        <goals>\\
\                            <goal>jar</goal>\\
\                        </goals>\\
\                    </execution>\\
\                </executions>\\
\            </plugin>\\
" pom.xml
like image 196
Mark Avatar answered Oct 02 '22 09:10

Mark


This should work:

sed -i '/Line to insert after/ i Line one to insert \
second new line to insert \
third new line to insert' file
like image 14
anubhava Avatar answered Oct 12 '22 15:10

anubhava


For anything other than simple substitutions on individual lines, use awk instead of sed for simplicity, clarity, robustness, etc., etc.

To insert before a line:

awk '
/Line to insert before/ {
    print "Line one to insert"
    print "second new line to insert"
    print "third new line to insert"
}
{ print }
' /etc/directory/somefile.txt

To insert after a line:

awk '
{ print }
/Line to insert after/ {
    print "Line one to insert"
    print "second new line to insert"
    print "third new line to insert"
}
' /etc/directory/somefile.txt
like image 8
Ed Morton Avatar answered Oct 12 '22 14:10

Ed Morton