I am trying to find all the files (ending with .c,.h and .java) that are in a folder or its subdirectories beginning with "new-". This is my current command: ls -R | egrep '.[.]c$|.[.]h$|.*[.]java$' What should I change?

  • 4
    You should change the question title to something more specific to your problem. :) Do not parse ls, use find. – Kamil Maciorowski Nov 30 '17 at 17:28
  • Does "new-" refer to to files to be found? or subdirectories to be searched? – Kamil Maciorowski Nov 30 '17 at 17:39
  • It's the first time I'm using this site :) It is requested that I use ls. It applies to subdirectories. – Kostakis Nov 30 '17 at 17:43
  • 1
    Please provide some example file paths that you want to locate. – Daniel B Nov 30 '17 at 17:47
  • Which of these directories would be valid places for the files you want to find? ./, ./new-a/, ./new-a/foo/, ./bar/new-b/, ./bar/new-b/baz/ – Kamil Maciorowski Nov 30 '17 at 18:09

Use find with -o (or operand) and (escaped) parentheses:

find $dir \( -name 'new*.java' -o -name 'new*.c' \)

Technically the parentheses aren't required unless you add other filters.

You can also use a regexp:

find . -regextype egrep -regex '.*/new-.*\.(java|c)'

(the regexp should match the full path, hence the .*/ at the start.


It's kind of ugly, but this would output each file extension you wanted in your current directory and it's sub-directories

find . -type f -name '*.c' && find . -type f -name '*.h' && find . -type f -name '*.java'


If you have to use ls then this might be what you are looking for:

ls | grep -r '*.c\|*.h\|*.java' | grep new-*
  • Thank you! But I need to use ls and the subdirectories have to start with "new-" – Kostakis Nov 30 '17 at 17:47
  • I updated my comment for doing it with ls, but its typically better to use find – Pythonic Nov 30 '17 at 18:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.