Creating Bash Script to retrieve data from XML fil

2019-09-20 11:41发布

I have an XML File like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<List>
    <Job id="1" name="John/>
    <Job id="2" name="Zack"/>
    <Job id="3" name="Bob"/>
</List>

I want to create a bash script where it pulls the id number from a specific name. For example, requesting John will out put 1. Is there any way I can do this?

标签: xml linux bash
2条回答
Evening l夕情丶
2楼-- · 2019-09-20 11:54

When parsing XML files, use a tool that understands xml. You could use xmlstarlet:

For example, saying:

xmlstarlet sel -t -v "/List/Job[@name=\"John\"]/@id" file.xml

would produce

1

BTW, your input isn't well-formed. You have a missing quote in

<Job id="1" name="John/>

It should be

<Job id="1" name="John"/>
查看更多
姐就是有狂的资本
3楼-- · 2019-09-20 11:59

Try something like

#!/bin/bash

name="$1"
while read -r line; do
  [[ $line =~ "name=\"$name\"" ]] && [[ $line =~ "Job id=\""([^\"]+) ]] &&  echo "${BASH_REMATCH[1]}"
done < file 

e.g. If file is your xml and John is fixed.

> ./abovescript John
1
> ./abovescript Zack
2
> ./abovescript Bob
3
查看更多
登录 后发表回答