The easiest way to get the FileFooter/Record
node's value into a shell variable in a script is by using an XML parser like xmlstarlet
.
The following assumes that the XML document is well-formed, which your example document isn't as it has multiple root tags (I'm presuming this is because you extracted the bits that you thought was most interesting). It also assumes that there is only one single FileFooter/Record
node, otherwise, you would have to iterate over the values.
value=$( xmlstarlet sel -t -v '//FileFooter/Record' file.xml )
The //FileFooter/Record
expression is the XPath of the node that we're interested in (actually the XPath of each FileFooter/Record
node in the whole document). With sel -t -v
, we tell xmlstarlet
that we want to extract the value (-v
) that we get from matching a particular or XPath (sel -t
).
Since the data in the question is missing a root tag, you may run the below command on it to insert the missing tag on the fly, parse the corrected document, and extract the wanted value inte the shell variable value
:
value=$(
{ echo '<root>'; cat file.xml; echo '</root>'; } |
xmlstarlet sel -t -v '//FileFooter/Record'
)
Assuming that the missing single root node is called root
, you could also extract the value using xq
(from https://kislyuk.github.io/yq/), an XML parser layer built around the JSON parser jq
.
value=$( xq -r '.root.FileFooter.Record' file.xml )
You could instead use .[].FileFooter.Record
if you don't want to type out the root node's name (this still assumes that FileFooter
is a node directly under the root node, though).
The command converts your XML file into JSON. If your XML document looks something like the following:
<?xml version="1.0"?>
<root>
<FileHeader>SampleFile</FileHeader>
<Name>aaaa</Name>
<Place>bufnkf</Place>
<Name> bjfbhj</Name>
<Place>bvdhbf</Place>
<FileFooter>
<Record>2</Record>
</FileFooter>
</root>
The xq
utility would convert it into the following JSON document:
{
"root": {
"FileHeader": "SampleFile",
"Name": [
"aaaa",
"bjfbhj"
],
"Place": [
"bufnkf",
"bvdhbf"
],
"FileFooter": {
"Record": "2"
}
}
}
xq
then calls jq
with the expression .root.FileFooter.Record
, which extracts the value.
{ echo '<tag>'; cat file.xml; echo '</tag>'; } | some_processing_command
.