sed error “unterminated 's' command” troub

2019-07-04 05:02发布

I am building a script that will, among other things, replace a pattern in an XML file with a folder path.

The sed command I am trying to use is:

SEDCMD="s|PATHTOEXPORT|$2|"

where $2 is the command-line parameter that has the folder path in it.

This is later called:

sed -e $SEDCMD $FILTER > $TEMPFILTER

However, on running the command, I am getting an "unterminated 's' command" error.

How can I get around this? I've tried changing the characters used to separate the regex (from / to |). And I've tried quoting (in different ways) the command-line parameter.

1条回答
神经病院院长
2楼-- · 2019-07-04 05:28

The shell is seeing the parsing the contents of $SEDCMD. If you’re using this from a shell script, including a Makefile, you should always protect all your expanded variables with double quotes. The double quotes will force variable interpolation but protect any shell metacharacter from further interpretation.

sed -e "$SEDCMD" "$FILTER" > "$TEMPFILTER"

I assume that $FILTER and $TEMPFILTER are filenames? I’ve quoted them, too, just in case they contain evil things like whitespace or other sorts of shell metacharacters; bizarre, yes, but it’s been known to happen. A regularly run rename 's/\s+/_/g' on filenames to clean them of whitespace, but for the others, you'll have to take a more careful approach; e.g., what to do with stars vs question marks vs brackets and parens, etc.

If you add -x and/or -v to your shell command line, you’ll get some trace debugging, which I think would likely have shown where you went amiss here.

查看更多
登录 后发表回答