【发布时间】:2013-12-06 15:12:50
【问题描述】:
我正在尝试查看传递给我的程序的变量(变量是 $1),并用所述特殊字符的引号形式替换任何特殊字符,以免特殊字符实际执行通常的操作.
我的代码是
#!/bin/sh
target="$1"
newtarget=`echo "$target" | sed -e s/\*/\\*/g`
newtarget=`echo "$newtarget" | sed -e s/\^/\\^/g`
newtarget=`echo "$newtarget" | sed -e s/\+/\\+/g`
newtarget=`echo "$newtarget" | sed -e s/\-/\\-/g`
newtarget=`echo "$newtarget" | sed -e s/\\/\\\/g`
newtarget=`echo "$newtarget" | sed -e s/\./\\./g`
newtarget=`echo "$newtarget" | sed -e s/\$/\\$/g`
newtarget=`echo "$newtarget" | sed -e s/\[/\\[/g`
newtarget=`echo "$newtarget" | sed -e s/\]/\\]/g`
sed s/"$newtarget"/"$2"/g "$3" > "$3.updated"
mv "$3.updated" $3
我的第一行,$target,应该查看目标字符串,看看字符串中是否有 *。如果有,它将用 * 替换它。在代码中,它出现为 * 然后是 \* 的原因是程序看不到 * 并认为它想实际使用 *,它只是将 * 看作是一个常规字符,用 .我在所有其他行中都做了同样的事情,但角色不同。在第一个之后,它应该签入 newtarget 并执行相同的操作,但使用不同的字符。
我的整个程序应该做的是,它传递了3个参数,第一个是要替换的字符串,第二个是要替换的字符串,第三个是文件名。所以到最后,如果文件最初是这样的
aa\^a*aa$aa[aaa$a]a
我提供
"a\^a*" "test"
作为参数,结果应该是
atestaa$aa[aaa$a]a
但我的代码仍然无法正常工作。我的代码有什么问题?我不知道我的 sed 语法是否适合编码,或者我的附加语句是否不起作用,或者我是否必须对某些特殊字符进行特殊引用。
编辑:我知道我应该能够像我一样使用多个 sed 命令来做到这一点,但我不知道为什么它们不能正常工作,所以我很确定这与我的引用有关在“newtarget=”行末尾的实际 sed 命令中。
EDIT2:我现在在我的代码中引用了我的 sed 参数,但它仍然无法正常工作。我需要引用某些特殊字符的特殊方法吗?我认为在每个字符前面加上反斜杠会正确引用它。
#!/bin/sh
target="$1"
newtarget=`echo "$target" | sed -e 's/\*/\\*/g'`
newtarget=`echo "$newtarget" | sed -e 's/\^/\\^/g'`
newtarget=`echo "$newtarget" | sed -e 's/\+/\\+/g'`
newtarget=`echo "$newtarget" | sed -e 's/\-/\\-/g'`
newtarget=`echo "$newtarget" | sed -e 's/\\/\\\/g'`
newtarget=`echo "$newtarget" | sed -e 's/\./\\./g'`
newtarget=`echo "$newtarget" | sed -e 's/\$/\\$/g'`
newtarget=`echo "$newtarget" | sed -e 's/\[/\\[/g'`
newtarget=`echo "$newtarget" | sed -e 's/\]/\\]/g'`
sed s/"$newtarget"/"$2"/g "$3" > "$3.updated"
mv "$3.updated" $3
【问题讨论】:
-
将参数引用到
sed -e。顺便说一句,您也可以将它们合并为一个:sed =e 's/\*/\\&/g' -e 's/\^/\\&/g' …甚至sed -e 's/[][*^+\\.$-]/\\&/g'。您还需要转义斜杠(分隔符)。 -
我尝试了你给我的最后一段代码,但我无法让它工作,所以我回到我的原始代码,只是引用了你说的 sed -e 参数,但我仍然收到错误消息。当您说我需要转义斜杠分隔符时,您是指在我的所有行中,还是在我有很多行的行中('s/\\/\\\/g')