Extract an attribute value from XML
Use an XML parser for parsing XML data. With xmlstarlet it just becomes an XPath exercise:
$ branch=$(xmlstarlet sel -t -v '//blah1[@name="andy"]/@branch' file.xml) $ echo $branch master
grep -Pio 'name="andy".*branch="\K[^"]*' file
-Penable perl regular expressions (PCRE)
-oprint only matched parts
In the regex, the
\K is a zero-width lookbehind to match the part before the
\K, but to not include it in the match.
Use xmllint to extract the value of the attribute using XPath:
xmllint --xpath 'string(/blah/blah1[@name="andy"]/@branch)' file.xml
It's better to use an XML parser to process XML since the order of the attributes can change and line breaks could be inserted resulting in the name and branch attributes being in different lines of the file.