如何在 BSD 上的 csh 中使用 sed 将一行替换为两行?

如何在 BSD 上的 csh 中使用 sed 将一行替换为两行?

我这里有一个非常简单的文本文件,其中包含以下内容

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 上运行sedcsh在基本系统上进行了测试。

相关内容