Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex in bash to find files

Basically what I am trying to do is list the contents of the current directory that has a certain extension (in my case .c files).

So what I thought would work is:

ls | grep .\*\.c

And it mainly works but also returns files that end in c like

  1. music (which is a directory)
  2. test.doc

Is there a problem with my regex because I cannot see it.

Many Thanks

like image 207
djjavo Avatar asked Oct 26 '25 10:10

djjavo


2 Answers

You can simply use ls *.c to list all files in the current directory having .c extension.

like image 188
Andrew Logvinov Avatar answered Oct 29 '25 02:10

Andrew Logvinov


Here's what you can do:

find -name "*.c"

and it will find all files with the .c extension for you, recursively from the current working directory.

Alternatively, if you want non-recursive and want to do it with ls, you can do:

ls *.c

If you want to know how to apply regex with grep to a ls search result (even though this is more cumbersome):

ls | grep ".*\.c$"

Regexplanation:

  • . - match any character
  • .* - match any character zero or more times
  • .*\. - match any character zero or more times, then match a . literally (specified by "escaping" it with \)
  • ".*\.c - match any character zero or more times, then match a . literally, then match the char c
  • .*\.c$ - match any character zero or more times, then match a . literally, then match the char c; and only if that is the end of the pattern (there are no more things after that). $ is the regex anchor for "the end".
like image 37
sampson-chen Avatar answered Oct 29 '25 00:10

sampson-chen