2

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

MapName:abc
someDiffName=someDiffValue
x=3
y=6
NeedyMappedName=NeedyMappedValue
.
.
Flag=true

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

abc,NeedyMappedValue

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?

  • 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
  • 1
    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
3

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
  • 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 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.