Shell – How to use multiline as group-separator in grep

grepquotingshell

In grep you can use --group-separator to write something in between group matches.

This comes handy to make it clear what blocks do we have, especially when using -C X option to get context lines.

$ cat a
hello
this is me
and this is
something else
hello hello
bye
i am done
$ grep -C1 --group-separator="+++++++++" 'hello' a
hello
this is me
+++++++++
something else
hello hello
bye

I learnt in Using empty line as context "group-separator" for grep how to just have an empty line, by saying --group-separator="".

However, what if I want to have two empty lines? I tried saying --group-separator="\n\n" but I get literal \ns:

$ grep -C1 --group-separator="\n\n" 'hello' a
hello
this is me
\n\n
something else
hello hello
bye

Other things like --group-separator="\nhello\n" did not work either.

Best Answer

Ooooh I found it, I just need to use the $'' syntax instead of $"":

$ grep -C1 --group-separator=$'\n\n' 'hello' a
hello
this is me



something else
hello hello
bye

From man bash:

QUOTING

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded as follows:

(...)
\n     new line
Related Question