2

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$" 
5
  • . matches any character. Try [.] or \. Also, -regex matches the full path, not the filename. Commented Jun 11, 2015 at 12:27
  • I already try this. But it does not work Commented Jun 11, 2015 at 12:28
  • @Mohan As knittl said find doesn't print just the filename, so something like this would work: find -type f -regex '^[.][/][0-9].*.c' Commented Jun 11, 2015 at 12:32
  • This 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$". Commented Jun 11, 2015 at 13:56
  • You 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'... Commented Jun 11, 2015 at 15:47

2 Answers 2

2

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...

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.