Skip to main content
added 314 characters in body
Source Link
pLumo
  • 23.2k
  • 2
  • 43
  • 70

Use an xml parser, e.g. xmlstarlet:

xmlstarlet sel -t -m '//fields' -v 'fullName' -n file

Note that your xml file should be valid, which it is not for your example as your missing a root tag. The following will work with above command:

<root>
<fields>
    <fullName>ABC</fullName>
    <trackFeedHistory>false</trackFeedHistory>
    <type>TY</type>
</fields>

<fields>
    <fullName>DEF</fullName>
    <trackFeedHistory>false</trackFeedHistory>
    <type>XY</type>
</fields>
</root>

Output:

ABC
DEF

Thanks to @roaimas comment, I created a for loop with the results from xmlstarlet without knowing the number of fields:

numFields=$(xmlstarlet sel -t -m '//fields' -o "." file | wc -c)
for i in $(seq 1 $numFields); do
    var=$(xmlstarlet sel -t -m "//fields[$i]" -v "fullName" file)
    printf '%s\n' "$var" # or do something else
done

Use an xml parser, e.g. xmlstarlet:

xmlstarlet sel -t -m '//fields' -v 'fullName' -n file

Note that your xml file should be valid, which it is not for your example as your missing a root tag. The following will work with above command:

<root>
<fields>
    <fullName>ABC</fullName>
    <trackFeedHistory>false</trackFeedHistory>
    <type>TY</type>
</fields>

<fields>
    <fullName>DEF</fullName>
    <trackFeedHistory>false</trackFeedHistory>
    <type>XY</type>
</fields>
</root>

Output:

ABC
DEF

Use an xml parser, e.g. xmlstarlet:

xmlstarlet sel -t -m '//fields' -v 'fullName' -n file

Note that your xml file should be valid, which it is not for your example as your missing a root tag. The following will work with above command:

<root>
<fields>
    <fullName>ABC</fullName>
    <trackFeedHistory>false</trackFeedHistory>
    <type>TY</type>
</fields>

<fields>
    <fullName>DEF</fullName>
    <trackFeedHistory>false</trackFeedHistory>
    <type>XY</type>
</fields>
</root>

Output:

ABC
DEF

Thanks to @roaimas comment, I created a for loop with the results from xmlstarlet without knowing the number of fields:

numFields=$(xmlstarlet sel -t -m '//fields' -o "." file | wc -c)
for i in $(seq 1 $numFields); do
    var=$(xmlstarlet sel -t -m "//fields[$i]" -v "fullName" file)
    printf '%s\n' "$var" # or do something else
done
Source Link
pLumo
  • 23.2k
  • 2
  • 43
  • 70

Use an xml parser, e.g. xmlstarlet:

xmlstarlet sel -t -m '//fields' -v 'fullName' -n file

Note that your xml file should be valid, which it is not for your example as your missing a root tag. The following will work with above command:

<root>
<fields>
    <fullName>ABC</fullName>
    <trackFeedHistory>false</trackFeedHistory>
    <type>TY</type>
</fields>

<fields>
    <fullName>DEF</fullName>
    <trackFeedHistory>false</trackFeedHistory>
    <type>XY</type>
</fields>
</root>

Output:

ABC
DEF