How do I use grep to extract a specific field value from lines

雨燕双飞 提交于 2020-03-16 05:30:59

问题


I have lines in a file which look like the following

....... DisplayName="john" ..........

where .... represents variable number of other fields.

Using the following grep command, I am able to extract all the lines which have a valid 'DisplayName' field:

grep DisplayName="[0-9A-Za-z[:space:]]*" e:\test

However, I wish to extract just the name (ie "john") from each line instead of the whole line returned by grep. I tried piping the output into the cut command but it does not accept string delimiters.


回答1:


Specifically:

sed 's/.*DisplayName="\(.*\)".*/\1/' 

Should do, sed semantics is s/subsitutethis/forthis/ where "/" is delimiter. The escaped parentheses in combination with escaped 1 are used to keep the part of the pattern designated by parentheses. This expression keeps everything inside the parentheses after displayname and throws away the rest.

This can also work without first using grep, if you use:

sed -n 's/.*DisplayName="\(.*\)".*/\1/p'

The -n option and p flag tells sed to print just the changed lines.

More in: http://www.grymoire.com/Unix/Sed.html




回答2:


This works for me:

awk -F "=" '/DisplayName/ {print $2}'

which returns "john". To remove the quotes for john use:

awk -F "=" '/DisplayName/ {gsub("\"","");print $2}'


来源:https://stackoverflow.com/questions/3070141/how-do-i-use-grep-to-extract-a-specific-field-value-from-lines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!