Insert multiple lines of text before specific line using Bash

后端 未结 9 1445
猫巷女王i
猫巷女王i 2020-12-16 03:01

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:



        
相关标签:
9条回答
  • 2020-12-16 03:18

    When the lines to be inserted are the result of some command "mycmd" (like cat results.txt or printf "%s\n" line{1..3}), you can do

    sed -i 's/Line to insert after/r' <(cmd) file
    or 
    sed -i 's/Line to insert after/echo "&";cmd/e' file
    

    The last command can be simple modified when you want to insert before some match.

    0 讨论(0)
  • 2020-12-16 03:21

    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
    
    0 讨论(0)
  • This might work for you (GNU sed & Bash):

    sed -i $'/Line to insert after/a\line1\\nline2\\nline3' file
    
    0 讨论(0)
  • 2020-12-16 03:27

    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
    
    0 讨论(0)
  • 2020-12-16 03:30
    sed -i '/Line to insert after/ i\
    Line one to insert\
    second new line to insert\
    third new line to insert' /etc/directory/somefile.txt
    
    0 讨论(0)
  • 2020-12-16 03:33

    To be POSIX compliant and run in OS X, I used the following (single quoted line and empty line are for demonstration purposes):

    sed -i "" "/[pattern]/i\\
    line 1\\
    line 2\\
    \'line 3 with single quotes\`
    \\
    " <filename>
    
    0 讨论(0)
提交回复
热议问题