I am working on a linux shell script to find information in a xml file using grep. The information I need is the Username wipis_dxu without the tag. I am not allowed to use tools like xgrep or something else.
<Parameter displayName="Server" id="Server">
<value>dxstg.target_domain</value>
</Parameter>
<Parameter isRequired="true" displayName="User name" id="Username">
<value>wipis_dxu</value>
</Parameter>
<Parameter isRequired="true" displayName="Password" id="Password">
<value>wovon_man_nicht_reden_kann_darueber_muss_mann_schweigen</value>
</Parameter>
$ sed -nr '/Username/{n;s#.*>(.*)<.*#\1#p}' file
wipis_dxu
Brief explanation,
/Username/
: find Username
n
: Read the next line of input
s#.*>(.*)<.*#\1#p
: extract the string between > ... <
Don't use sed
and grep
to handle XML, use an XML-aware tool. For example, in a tool I maintain called xsh, you can write
xsh -I file.xml 'echo //Parameter[@id="Username"]/value'
GREP only
This is a bit tricky because grep matches line by line, and on the line of the username there is nothing specifically saying it's the username and not the password.
So you'll have to chain greps :
grep -A 1 "Username" file | grep -o -P '[^>]+(?=</v)'
grep -r "wipis_dxu"
Will search current directory and all sub-directories for "wipis_dxu".