From the following article, you’ll learn how to print lines between two patterns in bash.
I’ll show how to to extract and print strings between two patterns using sed and awk commands.
I’ve created a file with the following text.
It’ll be used in the examples below, to print text between strings with patterns.
I Love Linux
***** BEGIN *****
BASH is awesome
BASH is awesome
***** END *****
I Love Linux
Lets say we need to print only strings between two lines that contain patterns ‘BEGIN’ and ‘END’.
Print Lines Between Two Patterns with SED
With the sed command, we can specify the starting pattern and the ending pattern, to print the lines between strings with these patterns. The syntax and the example are shown below.
Syntax:
sed -n '/StartPattern/,/EndPattern/p' FileName
| Option |
Description |
| -n, –quiet, –silent |
Suppress automatic printing of pattern space |
| p |
Print the current pattern space |
Example:
sed -n '/BEGIN/,/END/p' info.txt
***** BEGIN *****
BASH is awesome
BASH is awesome
***** END *****
Print Lines Between Two Patterns with AWK
Similar to the sed command, we can specify the starting pattern and the ending pattern with the awk command.
Syntax:
awk '/StartPattern/,/EndPattern/' FileName
Example:
awk '/BEGIN/,/END/' info.txt
***** BEGIN *****
BASH is awesome
BASH is awesome
***** END *****