我正在使用 sed 编辑文本文件。命令:
sed -n -e '/pattern1/,/pattern2/p' test01.txt
显示模式 1 和模式 2 之间的线条。但是我怎样才能在此之后插入新行呢pattern2
?我的 sed 版本不承认“i\”作为行命令版本。我正在运行 FreeBSD 端口。
答案1
如果您只想在pattern2之后插入新行,那么这可以工作 -
sed '/pattern2/s/$/\n/' file
[jaypal:~/Temp] cat file
some text
some text
some text pattern1
some text p
some text p
some text p
some text pattern2
some text
some text
[jaypal:~/Temp] sed '/pattern2/s/$/\n/' file
some text
some text
some text pattern1
some text p
some text p
some text p
some text pattern2
some text
some text
i\
用于插入。它会插入before
一个地址。如果你需要一条新线,你可以使用\a
which is append
。
[jaypal:~/Temp] sed '/pattern2/ a\
' file
some text
some text
some text pattern1
some text p
some text p
some text p
some text pattern2
some text
some text
如果您想在 /pattern2/ 之后添加新行并查看它们之间的行,那么您可能可以执行以下操作 -
[jaypal:~/Temp] sed -e '/pattern2/G' -ne '/pattern1/,/pattern2/p' file
some text pattern1
some text p
some text p
some text p
some text pattern2
[jaypal:~/Temp]
类似的解决方案awk
-
[jaypal:~/Temp] cat file
some text
some text
some text pattern1
some text p
some text p
some text p
some text pattern2
some text
some text
[jaypal:~/Temp] awk '/pattern1/,/pattern2/ END{print ""}' file
some text pattern1
some text p
some text p
some text p
some text pattern2
[jaypal:~/Temp]