我花了一段时间来弄清楚如何做到这一点,所以发布以防其他人正在寻找相同的。
要在模式后添加换行符,您还可以说:
sed '/pattern/{G;}' filename
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.
编辑:
顺便说一句,这恰好包含在sed one liners中:
# insert a blank line below every line which matches "regex"
sed '/regex/G'
这个sed命令:
sed -i '' '/pid = run/ a\
\
' file.txt
找到以下行:pid = run
file.txt之前
; Note: the default prefix is /usr/local/var
; Default Value: none
;pid = run/php-fpm.pid
; Error log file
并在file.txt中的该行之后添加换行符
file.txt之后
; Note: the default prefix is /usr/local/var
; Default Value: none
;pid = run/php-fpm.pid
; Error log file
或者,如果要添加文本和换行符:
sed -i '/pid = run/ a\
new line of text\
' file.txt
file.txt之后
; Note: the default prefix is /usr/local/var
; Default Value: none
;pid = run/php-fpm.pid
new line of text
; Error log file
一个简单的替换效果很好:
sed 's/pattern.*$/&\n/'
示例:
$ printf "Hi\nBye\n" | sed 's/H.*$/&\nJohn/'
Hi
John
Bye
要符合标准,请用反斜杠换行符替换\ n:
$ printf "Hi\nBye\n" | sed 's/H.*$/&\
> John/'
Hi
John
Bye
sed '/pattern/a\\r' file name
它将在模式后添加一个返回,而g
将用一个空行替换该模式。
如果必须在文件末尾添加新行(空白),请使用以下命令:
sed '$a\\r' file name
另一种可能性,例如果您没有空保持寄存器,可以是:
sed '/pattern/{p;s/.*//}' file
说明:
/pattern/{...}
=应用命令序列,如果找到带有模式的行,
p
=打印当前行,
;
=命令之间的分隔符,
s/.*//
=替换模式寄存器中没有任何内容的东西,
然后自动打印空模式寄存器作为附加行)