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

2
  • 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 Bot
    Commented Feb 11, 2023 at 11:31
  • I've added details, is this fine?
    – Dhruv
    Commented Feb 11, 2023 at 11:59

1 Answer 1

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.

3

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .