grep
accepts a list of "patterns" (i.e. one or more), separated by newline,
so grep $'a\n' infile
is the equivalent of
grep 'a
' infile
or grep -e 'a' -e '' infile
,
so you are providing the pattern a
(with no matches in this case)
and then a null pattern ''
which matches every line.
It's also mentioned in the GNU Grep Manual:
Why does the empty pattern match every input line?
The ‘grep’ command searches for lines that contain strings that
match a pattern. Every line contains the empty string,
so an empty pattern causes ‘grep’ to find a match on each line.
grep $'a\nb'
is the equivalent of
grep 'a
b' infile
or grep -e 'a' -e 'b' infile
.
Since there are no matches in your input, nothing is printed.
You ask
Since ''
matches every line then why doesn't -o
print anything?
The GNU man page says (emphasis mine):
-o
, --only-matching
Print only the matched (non-empty) parts of a matching line…
I don't have access to OSX right now
but I'm pretty sure their man page mentions this too…
It's also in the GNU Grep Manual.
Since the matched part of the matching lines is empty, nothing is printed.