![sed - 使用先前用另一个变量设置的变量时遇到问题](https://linux22.com/image/1180266/sed%20-%20%E4%BD%BF%E7%94%A8%E5%85%88%E5%89%8D%E7%94%A8%E5%8F%A6%E4%B8%80%E4%B8%AA%E5%8F%98%E9%87%8F%E8%AE%BE%E7%BD%AE%E7%9A%84%E5%8F%98%E9%87%8F%E6%97%B6%E9%81%87%E5%88%B0%E9%97%AE%E9%A2%98.png)
我想知道为什么当在 var, $thecolor 中设置值时 sed 不起作用?(我不能为此使用 HTML 解析器)。
无需使用变量设置 $STARTPATTERN 即可获得所需的结果:
$ STARTPATTERN='<span style=" color: #007000;">'
$ echo $STARTPATTERN
<span style=" color: #007000;">
$ echo $ENDPATTERN
</span>
$ echo '<p><span style=" color: #007000;">content words</span></p>' | sed -e "s%.*$STARTPATTERN\(.*\)$ENDPATTERN.*%\1%" # % is the delimiter for sed
content words
但是当使用变量时,颜色:
$ echo $thecolor
#007000
$ STARTPATTERN="<span style=\" color: $thecolor;\">"
$ echo $STARTPATTERN
<span style=" color: #007000;">
$ echo $ENDPATTERN
</span>
$ echo '<p><span style=" color: #007000;">content words</span></p>' | sed -e "s%.*$STARTPATTERN\(.*\)$ENDPATTERN.*%\1%"
<p><span style=" color: #007000;">content words</span></p>
新的信息:
$thecolor 生成为:
$ contentLine='<p><span style=" color: #007000;">content words</span></p>'
$ thecolor=$(echo $contentLine | sed -nr '/<span style=\" color:/ s/.*<span style=\" color:([^"]+).*/\1/p' | sed 's/;//')
我直接在终端中手动重新输入了 contentLine,但仍然出现同样的错误。
尝试 sed 的调试选项:
echo "$contentLine" | sed --debug -e "s%.*$STARTPATTERN\(.*\)$ENDPATTERN.*%\1%"
SED PROGRAM:
s/.*<span style=" color: #007000;">\\(.*\\)<\/span>.*/\1/
INPUT: 'STDIN' line 1
PATTERN: <p><span style=" color: #007000;">content words</span></p>
COMMAND: s/.*<span style=" color: #007000;">\\(.*\\)<\/span>.*/\1/
PATTERN: <p><span style=" color: #007000;">content words</span></p>
END-OF-CYCLE:
<p><span style=" color: #007000;">content words</span></p>
steeldriver 发布的解决方案有效,但我想了解为什么在 echo $STARTPATTERN 中没有显示添加或减去空格:
$ STARTPATTERN="<span style=\" color: $thecolor;\">" # a space between color:_$thecolor
$ echo $STARTPATTERN
<span style=" color: #007000;"> # space between color:_#007000
$ echo '<p><span style=" color: #007000;">content words</span></p>' | sed -e "s%.*$STARTPATTERN\(.*\)$ENDPATTERN.*%\1%"
<p><span style=" color: #007000;">content words</span></p> # undesirable results
$ STARTPATTERN="<span style=\" color:$thecolor;\">" # the space removed
$ echo $STARTPATTERN
<span style=" color: #007000;"> # STILL has space between color:_#007000
$ echo '<p><span style=" color: #007000;">content words</span></p>' | sed -e "s%.*$STARTPATTERN\(.*\)$ENDPATTERN.*%\1%"
content words # desirable results