How do I insert a newline/linebreak after a line u

2020-02-20 07:08发布

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

标签: bash shell sed zsh
5条回答
戒情不戒烟
2楼-- · 2020-02-20 07:30

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'
查看更多
在下西门庆
3楼-- · 2020-02-20 07:36

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
查看更多
爷的心禁止访问
4楼-- · 2020-02-20 07:37
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
查看更多
Bombasti
5楼-- · 2020-02-20 07:38

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)

查看更多
虎瘦雄心在
6楼-- · 2020-02-20 07:53

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
查看更多
登录 后发表回答