Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

grep

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.

like image 334
Stormshadow Avatar asked Jun 18 '10 13:06

Stormshadow


1 Answers

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}'
like image 188
Mike T Avatar answered Jan 01 '23 00:01

Mike T