【发布时间】:2021-04-27 13:01:22
【问题描述】:
我有一个目录,其中包含标题和有效负载 xml 文件,名为 like(没有 .xml 扩展名):
File1
File1_PAYLOAD
File2
File2_PAYLOAD
我需要检查头文件是否包含两个属性,如果存在,则文件应与其 PAYLOAD 文件一起移动到另一个目录。 我正在使用 xmllint --xpath 来检查属性,它有一个 headers 标签,里面是一堆 header 标签,我的查询:
xmllint --xpath "boolean(//*[local-name()='headers' and *[local-name()='header'][@name='Type' and @value='AAAA'] and *[local-name()='header'][@name='Update' and @value='DONE']])
xpath 查询工作正常,并根据属性是否存在返回真/假。问题在于如何仅迭代头文件并移动它们。我尝试使用 find 之类的:
#!/bin/bash
dest="/tmp/proc"
loc="/tmp/files"
find $loc -maxdepth 1 -mindepth 1 ! -name '*_PAYLOAD' -exec xmllint --xpath "boolean(//*[local-name()='headers' and *[local-name()='header'][@name='Type' and @value='AAAA'] and *[local-name()='header'][@name='Update' and @value='DONE']]) " {} \; -exec mv {} $dest \; -exec mv {}_PAYLOAD $dest \;
但是,即使我的 xpath 查询返回 false,此查询也会移动文件,我认为 find -exec 可能会将 true/false 作为字符串返回,因此为 true,并且仍继续执行下一个 exec。所以我尝试使用 sh -c find,这样我就可以合并某种 if 和 else 结构:
#!/bin/bash
dest="/tmp/proc"
loc="/tmp/files"
find $loc -maxdepth 1 -mindepth 1 ! -name '*_PAYLOAD' -exec sh -c '
for file do
stat=$(xmllint --xpath "boolean(//*[local-name()='headers' and *[local-name()='header'][@name='Type' and @value='AAAA'] and *[local-name()='header'][@name='Update' and @value='DONE']]) " "$file" | grep 'true' | wc -l)
if [ "$stat" -eq 1 ]
mv "$file" "$dest"
mv "$file"_PAYLOAD "$dest"
done' sh {} \;
但这给出了一个错误:
sh: -c: line 6: syntax error near unexpected token `done' sh: -c: line 6: `done'
【问题讨论】: