14

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.

fedorqui
  • 7,861
  • 7
  • 36
  • 74

2 Answers2

18

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
fedorqui
  • 7,861
  • 7
  • 36
  • 74
1

I suggest to use echo -e or printf with \\n for new-line.

Example (with echo -e):

$ grep -C1 --group-separator="$(echo -e line1\\n\\nline2)" 'hello' a
hello
this is me
line1
line2
something else
hello hello
bye

Example (with printf):

$ grep -C1 --group-separator="$(printf hello\\nfedorqui)" 'hello' a
hello
this is me
hello

fedorqui
something else
hello hello
bye

One advantage is we are using double quote. (hence variable expansion, etc. work)

Pandya
  • 24,618
  • I don't think it is necessary to use printf or echo. In your case, grep -C1 --group-separator=$'hello\nfedorqui' 'hello' a is equivalent. – fedorqui Jun 16 '15 at 09:38
  • @fedorqui yes, let me delete my redundant answer! – Pandya Jun 16 '15 at 09:44
  • Thanks however for the effort, if I hadn't found the $'' yours would be the good way to go! – fedorqui Jun 16 '15 at 09:46
  • @fedorqui Btw, I found failure with$'$var' (unable to expand/print value of variable if set by single quote!) right? whereas "$(echo $var)" can work. – Pandya Jun 16 '15 at 09:50
  • Yes, this is right. But you can then say $'"$var"'. That is $' + "$var" + '. – fedorqui Jun 16 '15 at 09:54
  • @fedorqui no you've end single quote like: $'sting1'"$var"'$string' – Pandya Jun 16 '15 at 11:16
  • You are right, I didn't test properly. --group-separator=$''"$var"'' works fine and so --group-separator=$"$var" does. – fedorqui Jun 16 '15 at 11:21