Regular Expression in Find command
Solution 1
It's because the regex option works with the full path and you specified only the file name. From man find
:
-regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named './fubar3', you can use the regular expression '.*bar.' or '.*b.*3', but not 'f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions, but this can be changed with the -regextype option.
Try with this:
find -type f -regex ".*/[0-9][^/]+\.c$"
where you explicitly look for a string where "the format of your filename follows any string that terminates with a slash"
UPDATE: I made a correction to the regex. I changed .*
in the filename to [^\]+
as after "any string that terminates with a slash" we don't want to find a slash in that part of the string because it wouldn't be a filename but another directory!
NOTE: The matching .*
can be very harmful...
Solution 2
Just use -name
option. It accepts pattern for the last component of the path name as the doc says:
-name pattern True if the last component of the pathname being examined matches pattern. Special shell pattern matching characters (``['', ``]'', ``*'', and ``?'') may be used as part of pattern. These characters may be matched explicitly by escaping them with a backslash (``\'').
So:
$ find -type f -name "[0-9]*.c"
should work.
Mohan
Updated on June 04, 2022Comments
-
Mohan almost 2 years
I want to list out the files which starts with a number and ends with ".c" extension. The following is the find command which is used. But, it does not give the expected output.
Command:
find -type f -regex "^[0-9].*\\.c$"
-
knittl almost 9 years
.
matches any character. Try[.]
or\.
Also,-regex
matches the full path, not the filename. -
Mohan almost 9 yearsI already try this. But it does not work
-
DBedrenko almost 9 years@Mohan As knittl said find doesn't print just the filename, so something like this would work:
find -type f -regex '^[.][/][0-9].*.c'
-
Mohan almost 9 yearsThis also does not give expected output. Because "./<directory name>/..../<filename>". You syntax will work only when the command executed within the same directory. for recursive search the following is the command which gives expected output. find -type f -regex ".*/[0-9].*\.c$".
-
twalberg almost 9 yearsYou could dispense with the regex here, as it seems to be complicating things, and just use a glob pattern, as in
find -type f -name '[0-9]*.c'
...
-