karunakar
karunakar

Reputation: 327

Grep for a word after matching a pattern and print

Say I have a file name foo.txt, and it contains the following information.

Notification are enabled
Notification:445
Mode: valid
Bookmark are enabled
Bookmarks:556
Mode: Invalid
Question are enabled
Question:667
Mode: Unknown

I want to grep/awk/sed the below information. I need the result like

                   "Notification is Valid"
                   "Bookmark is Invalid"
                   "Question is Unknown"

If you need anything else please let me know. Thank you.

Upvotes: 0

Views: 443

Answers (2)

Yves P
Yves P

Reputation: 1

Assuming foo.txt and we want to extract the 1st and last words of every 3 lines that contains 6 "groups" of separated by space of \n char expressions, using xargs:

xargs -n6 < foo.txt

"linearize" the content, and gives:

Notification are enabled Notification:445 Mode: valid
Bookmark are enabled Bookmarks:556 Mode: Invalid
Question are enabled Question:667 Mode: Unknown

pipe this content to awk:

xargs -n6 < foo.txt | awk '{print $1" is "$6}'

it gives something, I guess, closed to what you are looking for:

Notification is valid
Bookmark is Invalid
Question is Unknown

HTH

Upvotes: 0

twalberg
twalberg

Reputation: 62369

If I'm understanding what you want correctly, something like this might work:

awk '/enabled/{g=$1}/Mode:/{printf "%s is %s\n",g,$NF}' foo.txt

At least that should work given the example you've given. If you have to deal with disabled or anything else other than enabled, that'll make it a little more complex...

Upvotes: 1

Related Questions