Print lines between (and including) two patterns
10,496
You are better off using awk or sed
awk '/CK$/,/D$/' file.txt
OR
sed -n '/CK$/,/D$/p' file.txt
If you insist on grep, 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 videos on Youtube
Author by
Rana Khan
Updated on September 18, 2022Comments
-
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 hasD
at the end. I triedgrep "$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 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 over 10 yearsit 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 over 10 years@RahulPatil, added some explanation :-)
-
Rana Khan over 10 years@RohitPatil, I want to delete the matching selection from the file. can i do that?
-
Mathias Begert over 10 years@RanaKhan, what does the first line come back stating when you run
sed --version
on your system? -
Rana Khan over 10 yearsso 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 over 10 yearsthis does not delete this block. it only shows it
-
Mathias Begert over 10 years