简体   繁体   中英

grep with regular expressions won't see files

I am constantly having these problems with grep. It is as if sometimes it just stops working for no apparent reason. I have a number of files in a directory, say: car1, car2, car3..., car9.txt

When I type egrep "blabla" car[0-9][0-9]*.txt I get: "No such file or directory" The same thing happens with the "+" sign.

Why am I not seeing the single digit files here?

The shell applies wildcard expansion to the command line, not regular expressions. See also man 7 glob for more details.

Thus, * means "zero or more (any) characters" but does not mean "zero or more of the previous entity" and hence does not apply to [0-9] , so what you're searching for is:

"car" [any of 0-9] [any of 0-9] (zero or more of any chars) ".txt"

which will not find any single-digit file names.

To find single-digit files, use:

egrep "blabla" car[0-9].txt

To find single-digit files or double-digit, use:

egrep "blabla" car[0-9].txt car[0-9][0-9].txt

or try the following:

egrep "blabla" car[0-9]*.txt

which will may capture more than just car [any digits] .txt but it is an approximation that may work in this case, depending on the other contents of your directory.

Note that grep applies regular expression matching to its parameter, in this case "blabla" but that happens after shell processing has happened.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM