awk/sed get text between two patterns/strings

By using awk/sed command we can get text between two patterns/strings.

I have file with names.txt with following content:

uk
us
india
obama
putin
vatican

With following sed/awk commands I will show how to get text from india to putin:

With sed:

Syntax:

$ sed -n "/Pattern1/,/Pattern2/p" inputFile

Example:

$ sed -n "/india/,/putin/p" namex.txt

Output:

india
obama
putin

With awk:

Syntax:

$ awk "/Pattern1/,/Pattern2/ { print }" inputFile

Example:

$ awk "/Pattern1/,/Pattern2/ { print }" names.txt

Output:

india
obama
putin

Above awk example will work with gawk.

To install gawk use following command:

$ sudo apt-get install gawk

One comment on “awk/sed get text between two patterns/strings

  1. Pingback: Useing bash variable with awk | Sany's Linux and Open Source Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s