![如何在 BSD 上的 csh 中使用 sed 将一行替换为两行?](https://linux22.com/image/117853/%E5%A6%82%E4%BD%95%E5%9C%A8%20BSD%20%E4%B8%8A%E7%9A%84%20csh%20%E4%B8%AD%E4%BD%BF%E7%94%A8%20sed%20%E5%B0%86%E4%B8%80%E8%A1%8C%E6%9B%BF%E6%8D%A2%E4%B8%BA%E4%B8%A4%E8%A1%8C%EF%BC%9F.png)
我这里有一个非常简单的文本文件,其中包含以下内容
line1
line2
line3
line4
我想通过 sed(或其他一些应用程序)修改内容,所以它变成
line1
line2
#this line was added by sed
line3
line4
所以我尝试了sed -e "s/line2/line2\\n#this line was added by sed/" my-text-file-here.txt
,但输出是:
line1
line2\n#this line was added by sed
line3
line4
关于如何正确执行的任何想法?谢谢
答案1
使用 GNU sed,您的代码可以正常工作:
$ sed -e 's/line2/line2\n#this line was added by sed/' file
line1
line2
#this line was added by sed
line3
line4
然而,对于 BSD sed,\n
在替换文本中不被视为换行符。如果您的 shell 是 bash,一个好的解决方法是$'...'
插入换行符:
$ sed -e $'s/line2/line2\\\n#this line was added by sed/' file
line1
line2
#this line was added by sed
line3
line4
除了bash之外,zsh和ksh也支持$'...'
。
另一种选择是插入真正的换行符:
$ sed -e 's/line2/line2\
#this line was added by sed/' file
line1
line2
#this line was added by sed
line3
line4
更新:在 csh 中,最后一个选项需要额外的\
:
% sed -e 's/line2/line2\\
#this line was added by sed/' file
line1
line2
#this line was added by sed
line3
line4
答案2
看起来你想要A确实是pend命令。使用 Bash 或任何支持的 shell $'\n'
(大多数都支持):
sed $'/line2/a\\\n#this line was added by sed\n' file.txt
或者,更易读的是,使用 sed 命令文件:
/line2/a\
#this line was added by sed
显示完整方法:
$ cat file.txt
line1
line2
line3
line4
$ cat sedfile
/line2/a\
#this line was added by sed
$ sed -f sedfile file.txt
line1
line2
#this line was added by sed
line3
line4
$
答案3
这是假设csh
外壳:
简单地追加一行又一行:
% sed '/line2/a\\
# new line here\
' file
line1
line2
# new line here
line3
line4
要在另一行之前插入一行:
% sed '/line3/i\\
# new line here\
' file
line1
line2
# new line here
line3
line4
要使用以下命令用两个新行替换一行s
:
% sed 's/line2/&\\
# new line here/' file
line1
line2
# new line here
line3
line4
在 OpenBSD 6.1 上运行sed
并csh
在基本系统上进行了测试。