Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash, grep between two lines with specified string

Tags:

regex

grep

bash

Example:

a43 test1 abc cvb bnm test2 kfo 

I need all lines between test1 and test2. Normal grep does not work in this case. Do you have any propositions?

like image 782
user3162968 Avatar asked Mar 06 '14 10:03

user3162968


People also ask

How do I extract text between two words in Unix?

How do I extract text between two words ( <PRE> and </PRE> ) in unix or linux using grep command? Let us see how use the grep command or egrep command to extract data between two words or strings. I also suggest exploring sed/awk/perl commands to extract text between two words on your Linux or Unix machine.

How do you get surrounding lines grep?

You can use option -A (after) and -B (before) in your grep command.


2 Answers

Print from test1 to test2 (Trigger lines included)

awk '/test1/{f=1} /test2/{f=0;print} f' awk '/test1/{f=1} f; /test2/{f=0}'  awk '/test1/,/test2/' 

test1 abc cvb bnm test2 

Prints data between test1 to test2 (Trigger lines excluded)

awk '/test1/{f=1;next} /test2/{f=0} f'  awk '/test2/{f=0} f; /test1/{f=1}'  

abc cvb bnm 
like image 98
Jotne Avatar answered Sep 20 '22 21:09

Jotne


You could use sed:

sed -n '/test1/,/test2/p' filename 

In order to exclude the lines containing test1 and test2, say:

sed -n '/test1/,/test2/{/test1/b;/test2/b;p}' filename 
like image 33
devnull Avatar answered Sep 22 '22 21:09

devnull