1

我有一个 XML 文件目录。每个文件都有自己的唯一标识符。每个文件还包含一个或多个对其他文件(在单独的目录中)的引用,这些文件也具有唯一的 ID。

例如,我有一个名为example01.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>

如果一个文件有多个relatedFiles/otherFile元素,我需要为每个元素创建一个文件副本@href并重命名它,将唯一 ID@href的值与fileID. 因此,例如,我需要创建文件的两个副本example01.xml,一个名为abc01_xyz123.xml,另一个名为abc0002_xyz123.xmlotherFile这应该扩大以创建与元素一样多的副本。

现在,如果只有一个otherFile元素,我有一个 bash 脚本可以执行此操作,但我的脚本技能有限,我无法弄清楚如何处理多个otherFile元素。

#!/bin/bash
for f in *.xml; 
    do 
        name=`xpath -e 'string(//otherFile/@href)' $f 2> /dev/null`
        echo  "Moving" $f "to" ${name:3}.xml
        echo $name
        mv $f ${name:3}.xml
    done

提前致谢。

4

1 回答 1

1

像这样的东西可能会起作用:

#!/bin/bash

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 $3}'); do
    echo  "Moving $f to ${fid}_${uid}.xml"
    cp "$f" "${fid}_${uid}.xml"
  done
  rm "$f"
done
于 2013-08-10T22:48:31.800 回答