Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I retrieve matches from two repeated patterns: mappedname & its value in the text below?.


grep "MapName\|NeedyMappedName" fileName

If I run awk on the grep output, it will apply to each line so won't give the expected result.

The output I would like to get is


If I run grep "MapName\|NeedyMappedName" fileName' it will give me the required two lines. And when I extract the required values with awk -F ":" '{print $2}' it will give abc & I won't be able to extract the second required match, NeedyMappedValue from the filtered grep output. Is there any way to achieve this by running awk with some pattern with a different pattern for second line?

share|improve this question
Please clarify what you are asking, especially the awk part and fix "repeatitavie". – jlliagre Sep 30 '13 at 6:06
Once I run 'grep "MapName\|NeedyMappedName" fileName' will give me required two lines. And when I extarct required values with awk -F ":" '{print $2}' will give abc & I won't be able to extract required NeedyMappedValue from filtered grep output. Is there any way to achieve this by running awk with some pattern & awk with different pattern for second line – user1587504 Sep 30 '13 at 6:28
I provided above comment & I have received correct answer as can be seen below. Let me know if I need to edit query to be more specific – user1587504 Sep 30 '13 at 13:01
I edited your question. It should be reopened. – jlliagre Sep 30 '13 at 13:16
you could pipe grep's output through sed to transform the = to a : (or vice-versa), then you would have the same field separator for both lines. – cas Sep 30 '13 at 23:46
up vote 3 down vote accepted

I guess that's what you expect:

grep "MapName\|NeedyMappedName" fileName | awk -F: '
/MapName/ {printf "%s,",$2}
/NeedyMappedName/ {gsub("NeedyMappedName=","");printf "%s\n",$1}'

Edit: removing the unnecessary grep (thanks to Craig Sanders)

 awk -F: '
/MapName/ {printf "%s,",$2}
/NeedyMappedName/ {gsub("NeedyMappedName=","");printf "%s\n",$1}' fileName

and going a little further with awk (nawk on Solaris):

awk FS=":|=" '
/MapName/ {printf "%s,",$2}
/NeedyMappedName/ {printf "%s\n",$2}' fileName
share|improve this answer
the first grep isn't needed any more - awk is already ignoring all but the matching lines. – cas Sep 30 '13 at 23:48
@CraigSanders You are right, I overlook the redundancy. Thanks. – jlliagre Oct 1 '13 at 6:27

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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