-1

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?

2 Answers 2

4

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"/>
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.