Ram
Ram

Reputation: 143

Grep for a word and then grep the next occurring word

I would like to grep a word. Then, I would like to print the next matching line.

Ex: Input file

AAAA
BBBB
CCCC
BBBB
CCCC
EEEE
AAAA
WWWW
CCCC

Output

AAAA                        
CCCC              
AAAA  
CCCC

I would want to search for AAAA first every time and then print the first line with CCCC after it. Please help by using grep if possible.

Upvotes: 0

Views: 58

Answers (1)

John1024
John1024

Reputation: 113814

Answer for Revised Question

Using this as the sample file:

$ cat file2
AAAA
BBBB
CCCC
BBBB
CCCC
EEEE
AAAA
WWWW
CCCC

To print every line containing AAAA followed by the first line after it that contains CCCC, use:

$ sed -n '/AAAA/,/CCCC/ {/AAAA/p;/CCCC/p}' file2
AAAA
CCCC
AAAA
CCCC

Answer for Original Question

"I would want to search for AAAA first and then print the first line with CCCC after it."

Using this as the sample file:

$ cat file
AAAA
BBBB
CCCC
BBBB
CCCC
EEEE

To match the first line containing CCCC that occurs after the first line containing AAAA:

$ sed -n '/AAAA/,$ {/CCCC/{p;q}}' file
CCCC

How it works:

  • -n

    This tells sed not to print anything unless we explicitly ask it to.

  • /AAAA/,$ {/CCCC/{p;q}}

    /AAAA/,$ is a range. It specifies that the commands that follow it in braces are executed only if we between a line that matches AAAA and the last line in the file, denoted $.

    /CCCC/ is another condition. It tells sed to execute the commands which follow only if we are on a line that matches CCCC.

    {p;q} is a group of two commands. p tells sed to print the current line. q tells sed to quit (so no further lines will be read or matched).

Upvotes: 1

Related Questions