1

I was trying to solve some problem for searching using grep when I encountered this weird thing.

Suppose my file1.txt has these two lines

hello
to you

Whenever I

grep $'a\n' file1.txt

Output

hello to you

grep -o $'a\n' file1.txt

Output

Nothing

grep $'a\nb' file1.txt

Output

Nothing

Wouldn't $a\n mean a followed by newline, which is not in file but it still prints whole file. Why is this so?

P.S. - Even with -z option the behaviour is same

Dhruv
  • 13
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Feb 11 '23 at 11:31
  • I've added details, is this fine? – Dhruv Feb 11 '23 at 11:59

1 Answers1

0

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:

  1. 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.

don_crissti
  • 82,805