How do I insert a newline/linebreak after a line using sed

前端 未结 5 858
南方客
南方客 2020-12-28 13:43

It took me a while to figure out how to do this, so posting in case anyone else is looking for the same.

相关标签:
5条回答
  • 2020-12-28 13:55

    For adding a newline after a pattern, you can also say:

    sed '/pattern/{G;}' filename
    

    Quoting GNU sed manual:

    G
        Append a newline to the contents of the pattern space, and then append the contents of the hold space to that of the pattern space.
    

    EDIT:

    Incidentally, this happens to be covered in sed one liners:

     # insert a blank line below every line which matches "regex"
     sed '/regex/G'
    
    0 讨论(0)
  • 2020-12-28 13:57
    sed '/pattern/a\\r' file name 
    

    It will add a return after the pattern while g will replace the pattern with a blank line.

    If a new line (blank) has to be added at end of the file use this:

    sed '$a\\r' file name
    
    0 讨论(0)
  • 2020-12-28 14:05

    Another possibility, e.g. if You don't have an empty hold register, could be:

    sed '/pattern/{p;s/.*//}' file
    

    Explanation:
    /pattern/{...} = apply sequence of commands, if line with pattern found,
    p = print the current line,
    ; = separator between commands,
    s/.*// = replace anything with nothing in the pattern register,
    then automatically print the empty pattern register as additional line)

    0 讨论(0)
  • 2020-12-28 14:15

    A simple substitution works well:

    sed 's/pattern.*$/&\n/'
    

    Example :

    $ printf "Hi\nBye\n" | sed 's/H.*$/&\nJohn/'
    Hi
    John
    Bye
    

    To be standard compliant, replace \n by backslash newline :

    $ printf "Hi\nBye\n" | sed 's/H.*$/&\
    > John/'
    Hi
    John
    Bye
    
    0 讨论(0)
  • 2020-12-28 14:18

    This sed command:

    sed -i '' '/pid = run/ a\
    \
    ' file.txt
    

    Finds the line with: pid = run

    file.txt before

    ; Note: the default prefix is /usr/local/var
    ; Default Value: none
    ;pid = run/php-fpm.pid
    
    ; Error log file
    

    and adds a linebreak after that line inside file.txt

    file.txt after

    ; Note: the default prefix is /usr/local/var
    ; Default Value: none
    ;pid = run/php-fpm.pid
    
    
    ; Error log file
    

    Or if you want to add text and a linebreak:

    sed -i '/pid = run/ a\
    new line of text\
    ' file.txt
    

    file.txt after

    ; Note: the default prefix is /usr/local/var
    ; Default Value: none
    ;pid = run/php-fpm.pid
    new line of text
    
    ; Error log file
    
    0 讨论(0)
提交回复
热议问题