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 3 months
I want to start grepping from the lines that has
CKat the end of line and stop grepping when the line hasDat the end. I triedgrep "$CK" "$D" file..txt, but it didn't work.Input:
kkkkkkkkkkk jjjjjjjjjjjjjjjjjj gggggggggggg/CK JHGHHHHHHHH HJKHKKLKLLL JNBHBHJKJJLKKL JLKKKLLKJLKJ/D GGGGGGGGGGGGGG GGGGGGGGGGGGGGThe desired output:
gggggggggggg/CK JHGHHHHHHHH HJKHKKLKLLL JNBHBHJKJJLKKL JLKKKLLKJLKJ/D -
Mathias Begert about 9 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 about 9 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 about 9 years@RahulPatil, added some explanation :-) -
Rana Khan about 9 years@RohitPatil, I want to delete the matching selection from the file. can i do that?
-
Mathias Begert about 9 years@RanaKhan, what does the first line come back stating when you runsed --versionon your system? -
Rana Khan about 9 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 about 9 yearsthis does not delete this block. it only shows it
-
Mathias Begert about 9 years