Awk Print Line After A Matching /regex/

ht‮www//:spt‬.lautturi.com
Awk Print Line After A Matching /regex/

To print the line after a line that matches a specified pattern using the awk command, you can use the /regex/ syntax to specify the pattern, and the getline function to read the next line from the input.

For example, to print the line after a line that matches the regular expression /hello/, you could use the following awk command:

awk '/hello/ {getline; print}' filename

This will read each line of the filename file, and search for lines that match the pattern /hello/. When a line that matches the pattern is found, the getline function will read the next line from the input, and the print statement will print that line to the terminal.

Alternatively, you can use the NR (number of records) variable to keep track of the current line number, and the if statement to check if the current line number is one greater than the line number of the matching line. For example, to print the line after a line that matches the regular expression /hello/, you could use the following awk command:

awk '/hello/ {line_number=NR} NR==line_number+1 {print}' filename

This will read each line of the filename file, and search for lines that match the pattern /hello/. When a line that matches the pattern is found, the line_number variable will be set to the current line number. The if statement will then check if the current line number is one greater than the line number of the matching line, and if so, the print statement will print the current line to the terminal.

Created Time:2017-10-16 14:38:37  Author:lautturi