Insert multiple lines of text before specific line using Bash

后端 未结 9 1446
猫巷女王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:40

    This ll works from the first line.. For eg: If you want to insert from 3rd line of a file, replace "1i" to "3i".

    sed -i '1i line1'\\n'line2'\\n'line3' 1.txt 
    
    cat 1.txt
    
     line1
     line2
     line3
     Hai
    
    0 讨论(0)
  • 2020-12-16 03:40

    This can be easily done with Perl also

    $ cat MeanwhileInHell.txt
    Iran|XXXXXX|Iranian
    Iraq|YYYYYY|Iraquian
    Saudi|ZZZZZ|Saudi is a Rich Country
    USA|AAAAAA|USA is United States of America.
    India|IIII|India got freedom from British.
    Scot|SSSSS|Canada Mexio.
    $ perl -pe 'BEGIN {$x="Line one to insert\nLine 2\nLine3\n"} $_=$x.$_ if /USA/ ' MeanwhileInHell.txt
    Iran|XXXXXX|Iranian
    Iraq|YYYYYY|Iraquian
    Saudi|ZZZZZ|Saudi is a Rich Country
    Line one to insert
    Line 2
    Line3
    USA|AAAAAA|USA is United States of America.
    India|IIII|India got freedom from British.
    Scot|SSSSS|Canada Mexio.
    $
    
    0 讨论(0)
  • 2020-12-16 03:43

    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
    
    0 讨论(0)
提交回复
热议问题