List files of arbitrary depth according to a given pattern

I would like to list all the .c and .h files in the current directory or any of its subdirectories.
I tried ls -R *.c *.h or ls -R | *.c *.h but that doesn't work.

A related question : how to copy all the .c and .h files in the current directory or any of its subdirectories into another directory.

Try the find command.

I remember struggling with the find command a few months ago. Part of my problem comes from my having the Unix version of find (it's a Mac I'm using), which is the poor man's version of the Linux version of find.
The examples I could google about find were about the Linux version and don't work on my machine.
Although when I do

man find 

I get told that "The find utility recursively descends the directory tree for each path listed," but when I try

 find -f *.c *.h 

(or variants thereof, for example adding -E, using -name) I get exactly what I would get with

 ls *.c *.h

, i.e. only the files in the immediate directory are listed, not the one in the subdirectories.

When you use *.c and *.h without quotes, they are expanded by the shell before find ever sees them as operands. And, there is no need for any options for what you're trying to do. What you need is an expression that tells find what you want it to do.

To list files in the file hierarchy rooted in the current working directory that have names ending in .c or .h , that would be something like:

find . \( -name '*.c' -o -name '*.h' \)
1 Like