输出在bash使用XPath多个文件 [英] Outputting multiple files using XPath in bash

查看:190
本文介绍了输出在bash使用XPath多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a directory of XML files. Each file has its own unique identifier. Each file also contains one or more references to other files (in a separate directory), which also have unique IDs.

例如,我有一个名为 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 并将其重命名,用 FILEID 的值concatinating的唯一ID的值 @href 。因此,举例来说,我需要创建文件的两个副本 example01.xml ,一只叫 abc01_xyz123.xml 和另一名为 abc0002_xyz123.xml 。这应该扩大,因为有 otherFile 元素,创造尽可能多的拷贝。

If a file has multiple relatedFiles/otherFile elements, I need to create a copy of the file for each @href and rename it, concatinating the value of the unique ID in @href with the value of fileID. So, for example, I need to create two copies of file example01.xml, one named abc01_xyz123.xml and another named abc0002_xyz123.xml. This should scale up to create as many copies as there are otherFile elements.

现在,我有一个bash脚本,这是否如果只有一个 otherFile 元素,但我的脚本技能是有限的,我有麻烦搞清楚如何处理多个 otherFile 元素。

Right now, I have a bash script that does this if there is only a single otherFile element, but my scripting skills are limited and I am having trouble figuring out how to process multiple otherFile elements.

#!/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

先谢谢了。

推荐答案

这样的事情可能工作:

#!/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

这篇关于输出在bash使用XPath多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆