击:解析XML块到一个数组 [英] Bash: parsing XML block into an array
本文介绍了击:解析XML块到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个XML类文本文件,我想解析到一个数组。输入文件看起来像这样
I have an xml-like textfile which I would like to parse into an array. The input file looks like this
<AA>
<BB>content 1</BB>
</AA>
<AA>
<BB>content 2</BB>
</AA>
我要输出到像(即每个数组元素一个整体AA块):
I want the output to be like (meaning one whole AA-block per array element):
ARRAY[0]=<AA><BB>content 1</BB></AA>
ARRAY[1]=<AA><BB>content 2</BB></AA>
我试过
ARRAY=(`cat input.txt | grep -A 3 \<AA\>`)
但这只返回我每个数组元素一行。没有人有一个想法?
but this only returns me one line per array element. Does anyone have an idea?
推荐答案
XML和shell脚本不拌匀。如果可以,请考虑使用不同的文件格式或不同的脚本语言。
XML and shell scripts don't mix very well. If you can, consider using a different file format or a different scripting language.
(
IFS=$'\n'
ARRAY=($(grep -A 3 '<AA>' test.xml | awk '{printf "%s",$0} $0~"</AA>" {print}'))
for MATCH in "${ARRAY[@]}"; do
echo "$MATCH"
done
)
说明:
- IFS设置为
\\ n
控件数组元素是如何分道扬镳。我们不希望他们分开的空格或制表符,只是新行。 -
ARRAY =($(COMMAND))
捕捉命令的输出,并采用每行一个数组元素(因为我们设置IFS为\\ n
)。 -
{printf的%S,$ 0}
打印无尾随换行符的每一行。 -
$ 0〜&LT; / AA&gt;中{打印}
显示,每当我们看到一个关闭标签换行&LT; / AA方式&gt;
- 整个事情是在括号限制
$ IFS
变化的范围。我们不希望这种改变是永久的;最好将其限制在一个子shell。
- Setting IFS to
\n
controls how array elements are split apart. We don't want them split on spaces or tabs, just new lines. ARRAY=($(COMMAND))
captures COMMAND's output and takes each line as an array element (since we set IFS to\n
).{printf "%s",$0}
prints each line without the trailing newline.$0~"</AA>" {print}
prints a newline whenever we see a closing tag</AA>
.- The whole thing is in parentheses to limit the scope of the
$IFS
change. We don't want that change to be permanent; better to limit it to a sub-shell.
这篇关于击:解析XML块到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文