在 xmlstarlet (xpath) 表达式中引用 bash 变量或 bash 表达式

refer to bash variable or bash expression in xmlstarlet (xpath) expression

我想匹配 xml 属性中的日期。我尝试了以下命令:

xmlstarlet sel -t -v 'string(//*[local-name()="***"][@date="$(date +'%d %b %y')"]/@...)' file.xml

我还尝试用 bash 变量替换 bash 表达式。我使用了单引号和双引号、普通括号和大括号,没有骰子。

您需要在打开双引号之前关闭单引号;否则,单引号引用双引号,所以它们没有效果。

xmlstarlet sel -t -v \
  'string(//*[local-name()="***"][@date="'"$(date +'%b %d $y')"'"]/@...)' file.xml

# 'single-quoted content here"'"double-quoted content here"'"single-quoted content here'
# |                          ^|                            |^                          |
# |||||||||||||||||||||||||||||                            |||||||||||||||||||||||||||||

下面带有 ^ 个字符的 "s 作为 LITERAL:它们被围绕它们的单引号转义,因此成为传递给 xmlstarlet 的字符串的一部分。其他 ",没有被 ' 包围,是句法的:它们是对 shell 的指令,即 $(date) 扩展的内容不能分词或通配-扩大。 (管道显示字符串的哪些部分是单引号的,需要注意的是末尾的单引号是句法而不是文字,因此实际上并没有引用它们自己)。

查看 shell 连接成单个参数列表元素的不同引号子字符串可能更容易:

  • 'string(//*[local-name()="***"][@date="' - 单引号,包括 末尾的文字 "
  • "$(date +'%b %d $y')" - 双引号。
  • '"]/@...)' - 单引号,包括开头的文字 "