To be precise
Some text
begin
Some text goes here.
end
Some more text
and I want to extract entire block that starts from "begin" till "end".
with awk we can do like awk '/begin/,/end/' text
.
How to do with grep?
command linegreptext processing
To be precise
Some text
begin
Some text goes here.
end
Some more text
and I want to extract entire block that starts from "begin" till "end".
with awk we can do like awk '/begin/,/end/' text
.
How to do with grep?
Best Answer
Updated 18-Nov-2016 (since grep behavior is changed: grep with -P parameter now doesn't support
^
and$
anchors [on Ubuntu 16.04 with kernel v:4.4.0-21-generic])(wrong (non-)fix)note: for other commands just replace the '^' & '$' anchors with new-line anchor
'\n'
______________________________With grep command:
If you want don't include the patterns "begin" and "end" in result, use grep with Lookbehind and Lookahead support.
Also you can use
\K
notify instead of Lookbehind assertion.\K
option ignore everything before pattern matching and ignore pattern itself.\n
used for avoid printing empty lines from output.Or as @AvinashRaj suggests there are simple easy grep as following:
(?s)
tells grep to allow the dot to match newline characters.[\s\S]
matches any character that is either whitespace or non-whitespace.And their output without including "begin" and "end" is as following:
see the full test of all commands here (out of dated as grep behavior with -P parameter is changed)
Note:
^
point the beginning of a line and$
point the end of a line. these added to the around of "begin" and "end" to matching them if they are alone in a line.In two commands I escaped
$
because it also using for "Command Substitution"($(command)
) that allows the output of a command to replace the command name.From man grep: