Print lines between (and including) two patterns

10,496

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

Share:
10,496

Related videos on Youtube

Rana Khan
Author by

Rana Khan

Updated on September 18, 2022

Comments

  • Rana Khan
    Rana Khan over 1 year

    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
    
  • Mathias Begert
    Mathias Begert over 10 years
    @RahulPatil, that's because the OP stated 'start grepping from the lines that has "CK" at the end of line and stop grepping when the line has "D"'
  • Rahul Patil
    Rahul Patil over 10 years
    it seems me, you have strong understanding of regex.. I didn't understand that level, so could you please explain that last of PCRE grep
  • Mathias Begert
    Mathias Begert over 10 years
    @RahulPatil, added some explanation :-)
  • Rana Khan
    Rana Khan over 10 years
    @RohitPatil, I want to delete the matching selection from the file. can i do that?
  • Mathias Begert
    Mathias Begert over 10 years
    @RanaKhan, what does the first line come back stating when you run sed --version on your system?
  • Rana Khan
    Rana Khan over 10 years
    so basically the block that i want to remove has the first line that end with "CK \" and last line that end with "RD \". I am trying the following : sed -n '/CK \\$/,/D \\$/' script.tcl | more and it does not work , it says " sed: -e expression #1, char 16: missing command"
  • Rana Khan
    Rana Khan over 10 years
    this does not delete this block. it only shows it
  • Mathias Begert
    Mathias Begert over 10 years