1

我正在尝试使用 sed13替换:21

echo "for i in {1..5}; do commands for FILE13 > output_${i}; done" | sed 's/13/21/g'

我的输出如下所示:

for i in {1..5}; do commands for FILE21 > output_2; done

13被替换为,21但另外${i}被替换为2.

为什么会发生这种情况?以及如何停止 sed 替换 mu 花括号内容?

编辑

如果我的命令如下所示:

echo 'for i in {1..5}; awk'{( do commands)}' FILE13  > output_${i}; done' | sed 's/13/21/g'

而且我无法将双引号替换为单引号bash: syntax error near unexpected token('`

是唯一\用于转义大括号的解决方案吗?

4

3 回答 3

2

它不是 sed 替换花括号,而是外壳。将回显字符串的双引号更改为单引号。

相比:

$ echo "for i in {1..5}; do commands for FILE13 > output_${i}; done"
for i in {1..5}; do commands for FILE13 > output_; done

$ echo 'for i in {1..5}; do commands for FILE13 > output_${i}; done'
for i in {1..5}; do commands for FILE13 > output_${i}; done

如果您要回显的字符串本身包含单引号,则使用双引号并转义$或直接处理引号:

$ echo "for i in {1..5}; awk'{( do commands)}' FILE13  > output_\${i}; done"
for i in {1..5}; awk'{( do commands)}' FILE13  > output_${i}; done

$ echo 'for i in {1..5}; awk'"'"'{( do commands)}'"'"' FILE13  > output_${i}; done'
for i in {1..5}; awk'{( do commands)}' FILE13  > output_${i}; done
于 2013-02-11T15:30:21.777 回答
1

echo 的参数是文字字符串吗?然后:

echo "for i in {1..5}; do commands for FILE13 > output_\${i}; done" | sed 's/13/21/g'
于 2013-02-11T15:29:35.777 回答
1

您不能在单引号字符串中嵌入单引号。尝试:

echo 'for i in {1..5}; awk'"'"'{( do commands)}'"'"' FILE13  > output_${i}; done'
于 2013-02-11T17:57:53.533 回答