4

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

4 Answers 4

5

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

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

1 Comment

thanks for that andrew - did not know this. sorry if i wasn't clear in the question, but i would prefer to use ls | grep. many thanks for the help though, it is much appreciated :)
4

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

1 Comment

to mention that find searches recursively.
2

you are pretty close

ls | grep \\.c$

see the double backslashs

Comments

1

You need to escape your backslash:

ls | grep .*\\.c

8 Comments

many thanks for this. works perfectly. may i ask why you need to escape the backslash? from my understanding that regex means 0 or more of anything followed by \ followed by one of anything followed by c. Am I missing something here!
@djjavo normally in bash a backslash means "escape the next character", so to use an actual backslash for your regex you need to escape it.
yes i understand the \ being the escape character but i do not understand why we need to use an actual backslash in the regular expression (as its somecode.c not somecode\.c) am i being stupid because i do not understand!?
in regular expressions, a . matches any character, so you have to escape the . to match an actual .
yes i know that, but is you have "\\" then you are escaping the escape character??
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.