【问题标题】:Using XPath in bash with not()在带有 not() 的 bash 中使用 XPath
【发布时间】:2013-10-05 14:22:24
【问题描述】:

这是关于在 bash 中使用 XPath 的 previous question 的后续内容。

我有一组 XML 文件,其中大部分对与其他文件的关系进行编码:

<file>
    <fileId>xyz123</fileId>
    <fileContents>Blah blah Blah</fileContents>
    <relatedFiles>
        <otherFile href='http://sub.domain.abc.edu/directory/index.php?p=collections/pageview&amp;id=123‌​4'>
            <title>Some resource</title>
        </otherFile>
        <otherFile href='http://sub.domain.abc.edu/directory/index.php?p=collections/pageview&amp;id=4321'>
            <title>Some other resource</title>
        </otherFile>
    </relatedFiles>
</file>

previous question 的答案帮助我成功处理了这些文件中的大部分。但是,该集中的某些文件不包含任何 relatedFiles/otherFile 元素。我希望能够单独处理这些文件并将它们移动到“其他”文件夹中。我以为我可以使用 XPath not() 函数来做到这一点,但是当我运行脚本时,我得到了该行的“找不到命令”错误。

#!/bin/bash

mkdir other
for f in *.xml; do
  fid=$(xpath -e '//fileId/text()' "$f" 2>/dev/null)   
  for uid in $(xpath -e '//otherFile/@href' "$f" 2>/dev/null | awk -F= '{gsub(/"/,"",$0); print $4}'); do
    echo  "Moving $f to ${fid:3}_${uid}.xml"
    cp "$f" "${fid:3}_${uid}.xml"    
  done      
  if $(xpath -e 'not(//otherFile)' "$f" 2>/dev/null); then            
    echo  "Moving $f to other/${fid:3}.xml"
    cp "$f" "other/${fid:3}.xml"              
  fi  
  rm "$f"    
done

如何在 bash 中使用 XPath 过滤掉不包含某些元素的文件?提前致谢。

【问题讨论】:

    标签: xml bash shell xpath batch-processing


    【解决方案1】:

    $() 构造替代了命令的输出。因此,xpath 吐出的任何内容都将被替换,并且 shell 将尝试将其作为命令执行,这就是您收到错误消息的原因。

    由于xpath 似乎没有根据是否找到节点提供不同的退出代码,您可能只需将输出与某些内容进行比较,或测试是否为空:

    if [ -z "$(xpath -q -e '//otherFile' "$f" 2>/dev/null)" ]; then
    

    如果xpath 没有产生输出,这应该执行以下代码。要颠倒意思,请使用-n 而不是-z(不确定您想要哪个)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-29
      • 1970-01-01
      • 2010-12-05
      • 2012-06-16
      • 2016-10-11
      • 1970-01-01
      • 2020-01-22
      相关资源
      最近更新 更多