Search code examples
xmlshellsh

search for a particular string in xml and store it in a variable


I have certain lines in a file(props.xml) like these

<property name="property.first" value="some_value_here"/>
<property name="property.second" value="some_value_here/>

property.first and property.second are unique

How do I scrap out the some_value_here(we don't know) from that file taking the help of name="property.first" or name="property.second"

I just need help with cutting the line after grepping the intended line.


Solution

  • You can use a simple command line tool like sed to do this:

    sed -n '/name="property.first"/{s/.*value="\([^"]*\)".*/\1/p}' props.xml
    

    This will search for the name="property.first" line and then print out the value of the value attribute.

    Or you can use a simple regex to match the lines you're interested in, and then use a capturing group to extract the value:

     grep -E 'property\.(first|second)' props.xml | \
        sed -E 's/.*value="([^"]+)".*/\1/'