Awk Print Line After A Matching /regex/

To print the line after a pattern match in awk, you can use a flag variable to keep track of whether the current line matches the pattern, and print the next line if the flag is set.

Here’s an example:

Suppose we have a file called data.txt with the following content:

apple
banana
cherry
date
elderberry
fig

If we want to print the line after the word “cherry”, we can use the following awk command:

awk '/cherry/ {flag=1; next} flag {print; exit}' data.txt

This command does the following:

  • /cherry/ {flag=1; next}: When awk sees a line that contains the word “cherry”, it sets the flag variable to 1 and skips to the next line.
  • flag {print; exit}: If the flag variable is set, it prints the current line and exits. This ensures that only the first line after the pattern match is printed.

When you run the command, it should output:

date

This is the line after “cherry” in the data.txt file.

Leave a Comment