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?
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"/>
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