0

I have list of employees in following format

Name: 
Phone No:
Email: 

Name:
Address:
Phone No:
Email:

Name:
Country:
Address:
Phone No:
Email:

Name:
Address:

Name :
Email:
Address: 

All I want is that to get only Name and Email address.

I tried something like cat filename | grep -e ^Name: -e ^Email: but was not 100% successfull.

  • this should work 100%, can you provide us with error ? either lines missed to wrong lines found.(appart that you shoud not cat | grep ) – Archemar Mar 22 '16 at 15:12
2

Use | which is "or" operator for regex in the grep command. Also, no need for cat. grep can read from file directly.

grep '^Name:\|^Email:' filename
  • or grep -E '^(Name|Email):' filename. ^ and : are common to both sub-expressions, leaving only Name and Email as the non-fixed portion of the extended regular expression. – cas Mar 22 '16 at 22:21
0

If by "not 100% successful" you mean that you want only the values of the fields, without the field-names, then you need to use awk rather than grep.

e.g.

awk -F: '$1 ~ /^(Name|Email)$/ {print $2}' filename

Or, if you still want each record separated by a blank line:

awk -F: '$1 ~ /^(Name|Email)$/ {print $2}; /^[[:space:]]*$/ {print "\n"}' filename

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.