bash.替换为sed.线问题结束



我正在尝试使用sed搜索和替换文件。但是SED似乎很讨厌线路特殊字符。

text=$(shuf text.txt)
echo "This is text:
$text"
sed -i "s~%text%~$text~g" t.txt

这是我得到的:

This is text:
 line 2
 line 1
 line 3
 line 4
sed: -e expression #1, char 15: unterminated `s' command

我尝试用 r替换 n,但结果根本不满意。可以选择 tr' n','$',然后再向后进行,但似乎不对。

帮助?

使用sed and bash

由于您正在使用bash,请尝试:

sed -i "s~%text%~${text//$'n'/\n}~g" t.txt

${text//$'n'/\n}是Bash的模式替换的示例。在这种情况下,它将用后斜拉替换所有新线字符,然后用n替换为sed将其解释为newline。

示例

考虑此text变量:

$ echo "$text"
line 2
 line 1
 line 3
 line 4

和此输入文件:

$ cat t.txt
start
%text%
end

现在,运行我们的命令:

$ sed "s~%text%~${text//$'n'/\n}~g" t.txt
start
line 2
 line 1
 line 3
 line 4
end

当然要更改就位的文件,请添加-i选项。

使用awk

使用相同的text变量和t.txt文件如上所述:

$ awk -v new="$text" '{gsub(/%text%/, new)} 1' t.txt
start
line 2
 line 1
 line 3
 line 4
end

最新更新