(?s) tells grep to allow the dot to match newline characters. Or as suggests there are simple easy grep as following: grep -Pzo '(?s)^begin$.*?^end$' file \n used for avoid printing empty lines from output. \K option ignore everything before pattern matching and ignore pattern itself. grep -Pzo '(?<=^begin$\n)(.|\n)*(?=\n^end$)' fileĪlso you can use \K notify instead of Lookbehind assertion. If you want don't include the patterns 'begin' and 'end' in result, use grep with Lookbehind and Lookahead support. With grep command: grep -Pzo '^begin\$(.|\n)*^end$' file Note: for other commands just replace the '^' & '$' anchors with new-line anchor '\n' Updated 1 (since grep behavior is changed: grep with -P parameter now doesn't support ^ and $ anchors )( wrong (non-)fix) $ grep -Pzo 'begin(.|\n)*\nend' file