1

I have a file output.txt with content:

/usr/share/vim/vim80/doc/filetype.txt
/home/adminuser/trening/file1.txt
/home/adminuser/trening/file2.txt

Why grep "file1.txt" output.txt gives correct result and grep "file*.txt" output.txt or grep "file?.txt" output.txt gives no result?

Thank you in advance

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Glebster
  • 23
  • 5

2 Answers2

2

grep does not use glob pattern matching. It uses regex instead, so you should do:

grep "file.*\.txt" output.txt
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Thank you did not know that. Played around with it and got a new puzzle. According to what you say `grep file.\.* output.txt` should find only file1.txt and file2.txt However search result gives: `/help/files_write.txt /vim80/filetype.txt /home/file1.txt /home/file2.txt ` Why is it so? – Glebster Feb 27 '20 at 22:53
  • Please read about regex first. `*` matches zero to many occurrences of the preceding character, so `.*` matches any number of any characters, which is what the glob pattern `*` does in the one you included in your question. If you wish to match just one single character, your question would've included the glob pattern `file?.txt` instead, and the corresponding regex would be `file.\.txt`, where the unescaped `.` matches any character. – blhsing Feb 27 '20 at 22:56
  • Yes, I have read that article. But I do not understand why `\.*` is the same as `.*` As I understood `grep file.\..* output.txt` should search for file?.any characters after dot. But it is searching for any characters after file? Sorry, if this is confusing. – Glebster Feb 27 '20 at 23:09
  • @Glebster You should quote the regex, or the backslash would be interpreted by the shell and not get passed to `grep`. – blhsing Feb 27 '20 at 23:12
  • 1
    Attention to details is crutial with linux! Thank you – Glebster Feb 27 '20 at 23:38
  • Also read up on quotes at https://mywiki.wooledge.org/Quotes as I foresee those coming to bite you in the near future if you continue to use double quotes instead of single quotes around strings or scripts when you don't have a specific **need** to do so. – Ed Morton Feb 29 '20 at 15:14
0

The grep command handles the argument as regex, where the * has a different meaning than in the terminal (glob). Related: Using the star sign in grep

Lukr
  • 659
  • 3
  • 14