12

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.

0

2 Answers 2

14

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
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)

7
  • 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, 2015 at 9:38
  • @fedorqui yes, let me delete my redundant answer!
    – Pandya
    Jun 16, 2015 at 9:44
  • Thanks however for the effort, if I hadn't found the $'' yours would be the good way to go!
    – fedorqui
    Jun 16, 2015 at 9: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, 2015 at 9:50
  • Yes, this is right. But you can then say $'"$var"'. That is $' + "$var" + '.
    – fedorqui
    Jun 16, 2015 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.