使用 shell 中的 sed 来处理特殊等号

使用 shell 中的 sed 来处理特殊等号

我的环境:

我正在使用 Windows 上的命令解释器。

我使用安装的一些专有工具附带的 sh.exe。我不知道该 sh.exe 的详细信息,但查询其版本时我得到了以下信息:

>sh.exe --version
GNU bash, version 3.1.23(1)-release (i686-pc-msys)
Copyright (C) 2005 Free Software Foundation, Inc.

类似地,这是我对 sed 所得到的:

>sed --version
GNU sed version 4.2.1
Copyright (C) 2009 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE,
to the extent permitted by law.

GNU sed home page: <http://www.gnu.org/software/sed/>.
General help using GNU software: <http://www.gnu.org/gethelp/>.
E-mail bug reports to: <[email protected]>.
Be sure to include the word ``sed'' somewhere in the ``Subject:'' field.

我追求的是:

我希望能够使用匹配相等字符的 sed 命令并从 shell 脚本中执行此操作。

这按预期工作:

>echo "a=b" | sed "s/a=//"
"b"

如果 parse_trace.sh 包含

#!/bin/sh

sed "s/a//"

我也得到了我期望的:

>echo "a=b" | sh parse_trace.sh
"=b"

但是,将脚本的最后一行替换为:

sed "s/a=//"

导致

>echo "a=b" | sh parse_trace.sh
sed.exe: -e expression #1, char 5: unterminated `s' command

如果我改用

sed "s/a\=//"

我明白了

>echo "a=b" | sh parse_trace.sh
"==b"

我错过了什么?

更新

如果 = 符号不是模式中的最后一个字符,则在我的 shell 脚本中可以正确解释它。例如,如果脚本中的最后一行现在是:

sed "s/a=b//"

然后我得到:

echo "a=b" | sh parse_trace.sh
""

echo "a=bc" | sh parse_trace.sh
"c"

因此 =/ 中的某些内容会导致 DOS-SHELL 组合失败。

更新 2

>od -Ax -tx1z parse_trace.sh
000000 23 21 2f 62 69 6e 2f 73 68 0a 0a 73 65 64 20 22  >#!/bin/sh..sed "<
000010 73 2f 61 5c 3d 2f 2f 22 0a 0a                    >s/a\=//"..<
00001a

>echo "a=b" | sh -x parse_trace.sh
+ sed 's/a\=//'
"==b"

>od -Ax -tx1z parse_trace.sh
000000 23 21 2f 62 69 6e 2f 73 68 0a 0a 73 65 64 20 22  >#!/bin/sh..sed "<
000010 73 2f 61 3d 2f 2f 22 0a 0a                       >s/a=//"..<
000019

>echo "a=b" | sh -x parse_trace.sh
+ sed s/a=//
sed.exe: -e expression #1, char 5: unterminated `s' command

答案1

我不确定它是否会起作用,但我认为这是一个很好的尝试:

sed 's,a\x3d,,'

我在我的环境中尝试过,它有效。有两个原因可能是您遇到这种情况的原因:
a. 您使用的 sh 和 cmd 一起将 '/' 和 '\' 视为 sed 的两个分隔符。b
. 您使用了双引号,bash 将尝试在其中查找方程式和变量。

我自己经常使用 cmd 结合 shell 命令,我建议你试试 cygwin。将 cygin 的 bin 路径添加到 windows 的 PATH 中,效果会很好。但你需要小心 ESCAPE。

相关内容