How to insert a line using sed before a pattern and after a line number?

后端 未结 4 1350
我在风中等你
我在风中等你 2020-12-09 15:36

How to insert a line into a file using sed before a pattern and after a line number? And how to use the same in shell script?

This inserts a line before

相关标签:
4条回答
  • 2020-12-09 16:23

    Simple? From line 12 to the end:

    sed '12,$ s/.*Sysadmin.*/Linux Scripting\n&/' filename.txt
    
    0 讨论(0)
  • 2020-12-09 16:28

    You can either write a sed script file and use:

    sed -f sed.script file1 ...
    

    Or you can use (multiple) -e 'command' options:

    sed -e '/SysAdmin/i\
    Linux Scripting' -e '1,$s/A/a/' file1 ...
    

    If you want to append something after a line, then:

    sed -e '234a\
    Text to insert after line 234' file1 ...
    
    0 讨论(0)
  • 2020-12-09 16:30

    I assume you want to insert the line before a pattern only if the current line number is greater than some value (i.e. if the pattern occurs before the line number, do nothing)

    If you're not tied to sed:

    awk -v lineno=$line -v patt="$pattern" -v text="$line_to_insert" '
        NR > lineno && $0 ~ patt {print text}
        {print}
    ' input > output
    
    0 讨论(0)
  • 2020-12-09 16:37

    here is an example of how to insert a line before a line in a file:

    example file test.txt :

    hello line 1
    hello line 2
    hello line 3
    

    script:

    sed -n 'H;${x;s/^\n//;s/hello line 2/hello new line\n&/;p;}' test.txt > test.txt.2
    

    output file test.txt.2

    hello line 1
    hello new line
    hello line 2
    hello line 3
    

    NB! notice that the sed has as beginning a substitution of a newline to no space - this is necessary otherwise resulting file will have one empty line in the beginning

    The script finds the line containing "hello line 2", it then inserts a new line above -- "hello new line"

    explanation of sed commands:

    sed -n:
    suppress automatic printing of pattern space
    
    H;${x;s/test/next/;p}
    
    /<pattern>/  search for a <pattern>
    ${}  do this 'block' of code
    H    put the pattern match in the hold space
    s/   substitute test for next everywhere in the space
    x    swap the hold with the pattern space
    p    Print the current pattern hold space. 
    
    0 讨论(0)
提交回复
热议问题