Print lines between (and including) two patterns

awkgrepsedtext processing

I want to start grepping from the lines that has CK at the end of line and stop grepping when the line has D at the end. I tried grep "$CK" "$D" file..txt, but it didn't work.

Input:

kkkkkkkkkkk   
jjjjjjjjjjjjjjjjjj  
gggggggggggg/CK  
JHGHHHHHHHH   
HJKHKKLKLLL   
JNBHBHJKJJLKKL  
JLKKKLLKJLKJ/D  
GGGGGGGGGGGGGG  
GGGGGGGGGGGGGG

The desired output:

gggggggggggg/CK  
JHGHHHHHHHH   
HJKHKKLKLLL   
JNBHBHJKJJLKKL  
JLKKKLLKJLKJ/D

Best Answer

You are better off using or

awk '/CK$/,/D$/' file.txt

OR

sed -n '/CK$/,/D$/p' file.txt

If you insist on , here's a GNU grep way

grep -oPz '(?s)(?<=\n)\N+CK\n.*?D(?=\n)' file.txt

Here

-P activates perl-regexp

-z sets line separator to NUL. This forces grep to see the entire file as one single line

-o prints only matching

(?s) activates PCRE_DOTALL, so . finds any character or newline

\N matches anything except newline

.*? finds . in nongreedy mode

(?<=..) is a look-behind assertion

(?=..) is a look-ahead assertion

Related Question