Grep a word from XML file with grep/sed

2019-10-07 20:04发布

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>

4条回答
贼婆χ
2楼-- · 2019-10-07 20:29
grep -r "wipis_dxu"

Will search current directory and all sub-directories for "wipis_dxu".

查看更多
3楼-- · 2019-10-07 20:36
$ 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 > ... <
查看更多
Deceive 欺骗
4楼-- · 2019-10-07 20:37

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)'

查看更多
劫难
5楼-- · 2019-10-07 20:50

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'
查看更多
登录 后发表回答