sed command produces error when output reused (Escaping)

时间:2018-02-03 11:09:05

标签: bash sed escaping

My Bash script works through a top_directory and I need the path relative to the top_directory, as the whole tree might be copied somewhere else.

I am using sed to replace the path "$TOP" to the top_directory from the filename $F1. This works, but when I place my sed command in inverted quotes to set a shell-variable, I get an error from sed. My assumption is, that the inverted quotes require a rework on some of the escapes inside sed. But which?

Script Snippet

echo $F1
echo $TOP
echo $F1 | sed "s/${TOP//\//\\/}//g;s/^\///g;s/^/\"/g;s/$/\";/g"
echo fine
RELATIVE_PATH=` echo $F1 | sed "s/${TOP//\//\\/}//g;s/^\///g;s/^/\"/g;s/$/\"/g" `
echo bad

The first s remove the text stored in $TOP; the second s takes care of a leading slash; the third s creates a leading quote and the last a trailing quote.

OUTPUT:

/home/felix/data/media/music/branch/20170504/Music/Frank Reid/Frank Reid plays Just for You/04 Dorney Wood - S2x40 (digitized).mp3
/home/felix/data/media/music/branch/20170504/Music
"Frank Reid/Frank Reid plays Just for You/04 Dorney Wood - S2x40 (digitized).mp3";
fine
sed: -e expression #1, char 9: unknown option to `s'
bad

I also tried single quotes as escape character for the variable assignment and it failed. Also creating with sed a text like RELATIVE_PATH=".." and placing it in eval failed.

1 个答案:

答案 0 :(得分:1)

Sed允许使用与' /'不同的字符。作为表达式分隔符:s#pattern#subst#g。所以你的命令会更简单,因为你摆脱了$ TOP变量

中的转义和字符串替换

TOP='/aa/bb'; relative=$(echo "/aa/bb/cc" | sed -e "s#$TOP##g;"' s#^/##g; s#^#"#g; s#$#"#g'); echo $relative "cc"

此外,$()比反引号更易读。

更简单,因为你仍然得到一个带引号的字符串

TOP='/aa/bb'; relative=$(echo "/aa/bb/cc" | sed -e "s#$TOP##g;"' s#^/##g;'); echo "'$relative'" 'cc'