0

Examples from: Linux Journal article

The first two examples work, but the third does not, as expected from the article. Can someone explain why? I have tried on both Ubuntu 22.04.1 and RHEL9, with the same result.

My screen:

[primus@rhel9 sandbox]$ cat filename.doc 
The fast dog is fast.
The faster dogs are faster.
A sick dog should see a dogdoc.
This file is filename.doc.
[primus@rhel9 sandbox]$ grep "fast*" filename.doc 
The fast dog is fast.
The faster dogs are faster.
[primus@rhel9 sandbox]$ grep "dogs*" filename.doc 
The fast dog is fast.
The faster dogs are faster.
A sick dog should see a dogdoc.
[primus@rhel9 sandbox]$ grep "*.doc" filename.doc 
[primus@rhel9 sandbox]$ 
[primus@rhel9 sandbox]$ 

But as extended regex, the third example works:

[primus@rhel9 sandbox]$  
[primus@rhel9 sandbox]$ egrep "*.doc" filename.doc  
A sick dog should see a dogdoc.  
This file is filename.doc.  
[primus@rhel9 sandbox]$ grep -E "*.doc" filename.doc   
A sick dog should see a dogdoc.  
This file is filename.doc.  
[primus@rhel9 sandbox]$   
faszikam
  • 11
  • 1
  • 3
  • are you certain that `grep "dogs*" filename.doc` returned three lines? – jsotola Aug 23 '22 at 06:28
  • @jsotola, why would it not? `dogs*` matches on `dog` followed by 0 or more `s`s. `grep 'dogs*'` is equivalent to `grep dog`. While `*.doc` matches on a literal `*` followed by any single character followed by `doc`. `grep -E '*.doc'` would return an error as `*` doesn't follow anything. – Stéphane Chazelas Aug 23 '22 at 06:29
  • 2
    It looks like you're confusing regular expressions with shell glob patterns, even though the Linux Journal article you're linking to is exactly about how they are different. – Stéphane Chazelas Aug 23 '22 at 06:33
  • 3
    Yes, just had a look, that article is wrong on several accounts and misleading in a few others. I wouldn't recommend reading it. – Stéphane Chazelas Aug 23 '22 at 06:40
  • Sorry, my bad. `*.doc` is not a valid extended regexp, but `grep -E '*.doc'` is not *required* to return an error. Its behaviour is unspecified, and varies between implementations, some return an error, some (like GNU grep) treat it the same as `grep '.doc'` – Stéphane Chazelas Aug 23 '22 at 06:57
  • 3
    In any case `grep '*.doc'` (without `-E`) is required by POSIX to match on a literal `*` followed by a single character followed by a `.` as in BRE `*` matches itself if it's at the beginning of the regexp or following `\(`. – Stéphane Chazelas Aug 23 '22 at 06:59
  • 1
    Does this answer your question? [Why does my regular expression work in X but not in Y?](https://unix.stackexchange.com/questions/119905/why-does-my-regular-expression-work-in-x-but-not-in-y) – Gilles 'SO- stop being evil' Aug 23 '22 at 08:31

0 Answers0