2013-09-29 45 views
2

這是關於在bash中使用XPath的previous question的後續操作。在bash中使用XPath not()

我有一組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()函數做到這一點,但是當我運行該腳本時,我得到了該行的「command not found」錯誤。

#!/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篩選出不包含某些元素的文件?提前致謝。

回答

2

$()構造替代命令的輸出。因此,任何被xpath吐出來的東西都會被替換,並且shell會嘗試執行它作爲命令,這就是爲什麼你會收到錯誤信息。

由於xpath似乎並沒有提供基於節點是否找到一個不同的退出代碼,你可能只需要輸出的東西,或測試比較空:

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

這應該如果xpath未產生任何輸出,請執行以下代碼。要扭轉這種感覺,請使用-n而不是-z(不確定您打算使用哪一個)。