我想知道使用shellscript解析XML文件的最佳方法是什么?
如果你已经成功了,如果你能让我知道你是怎么做到的
aes*_*ede 22
这是一个完整的工作示例.
如果它只提取电子邮件地址,你可以执行以下操作:
1)假设XML文件spam.xml就像
<spam>
<victims>
<victim>
<name>The Pope</name>
<email>pope@vatican.gob.va</email>
<is_satan>0</is_satan>
</victim>
<victim>
<name>George Bush</name>
<email>father@nwo.com</email>
<is_satan>1</is_satan>
</victim>
<victim>
<name>George Bush Jr</name>
<email>son@nwo.com</email>
<is_satan>0</is_satan>
</victim>
</victims>
</spam>
Run Code Online (Sandbox Code Playgroud)
2)您可以使用以下简短的bash代码获取电子邮件并进行处理:
#!/bin/bash
emails=($(grep -oP '(?<=email>)[^<]+' "/my_path/spam.xml"))
for i in ${!emails[*]}
do
echo "$i" "${emails[$i]}"
# instead of echo use the values to send emails, etc
done
Run Code Online (Sandbox Code Playgroud)
这个例子的结果是:
0 pope@vatican.gob.va
1 father@nwo.com
2 son@nwo.com
Run Code Online (Sandbox Code Playgroud)
重要提示:
请勿将此用于严重事项.这对于玩游戏,获得快速结果,学习grep等都是可以的,但是你一定要寻找,学习和使用XML解析器进行制作(参见下面的Micha评论).
小智 5
一个相当新的项目是 xml-coreutils 包,它具有 xml-cat、xml-cp、xml-cut、xml-grep、...
http://xml-coreutils.sourceforge.net/contents.html