Using sed to insert file content

后端 未结 5 739
梦如初夏
梦如初夏 2020-11-30 07:54

I\'m trying to insert a file content before a given pattern

Here is my code:

sed -i \"\" \"/pattern/ {
i\\\\ 
r $scriptPath/adapters/default/permissi         


        
相关标签:
5条回答
  • 2020-11-30 08:30

    I tried Todd's answer and it works great,

    but I found "h" & "g" commands are ommitable.

    Thanks to this faq (found from @vscharf's comments), Todd's answer can be this one liner.

    sed -i -e "/pattern/ {r $file" -e 'N}' $manifestFile
    

    Edit: If you need here-doc version, please check this.

    0 讨论(0)
  • 2020-11-30 08:31

    CodeGnome's solution don't work, if the pattern is on the last line.. So I used 3 commands.

    sed -i '/pattern/ i\
            INSERTION_MARKER
            ' $manifestFile
    sed -i '/INSERTION_MARKER/r $scriptPath/adapters/default/permissions.xml' $manifestFile
    sed -i 's/INSERTION_MARKER//' $manifestFile
    
    0 讨论(0)
  • 2020-11-30 08:43

    I got something like this using awk. Looks ugly but did the trick in my test:

    command:

    cat test.txt | awk '
    /pattern/ {
        line = $0;
        while ((getline < "insert.txt") > 0) {print};
        print line;
        next
    }
    {print}'
    

    test.txt:

    $ cat test.txt
    some stuff
    pattern
    some other stuff
    

    insert.txt:

    $ cat insert.txt
    this is inserted file
    this is inserted file
    

    output:

    some stuff
    this is inserted file
    this is inserted file
    pattern
    some other stuff
    
    0 讨论(0)
  • 2020-11-30 08:47

    Just remove i\\.

    Example:

    $ cat 1.txt
    abc
    pattern
    def
    
    $ echo hello > 2.txt
    
    $ sed -i '/pattern/r 2.txt' 1.txt
    
    $ cat 1.txt
    abc
    pattern
    hello
    def
    
    0 讨论(0)
  • 2020-11-30 08:54

    In order to insert text before a pattern, you need to swap the pattern space into the hold space before reading in the file. For example:

    sed "/pattern/ {
             h
             r $scriptPath/adapters/default/permissions.xml
             g
             N
         }" "$manifestFile"
    
    0 讨论(0)
提交回复
热议问题