Using find and regular expressions

Hi

Could you please advise how can one extract from the output of

    find . -name "*.c" -print

only filenames in the current direcotry and not in its subdirectories?

I tried using (on Linux x86_64)

   find . -name "*.c" -prune

but it is not giving correct output.

Whereas I am getting following output

./file1.c
./child_dir/file1.c
./child_dir/file4.c
./child_dir/file2.c
./child_dir/file3.c
./file4.c
./file2.c
./file3.c

Other than prune, is it possible to pipe GREP with find to get desired output?

I think you can use "maxdepth" flag :slight_smile:

find ./* -prune -name "*.c" -type f

Dear Bipinajith,

I think -type f may not be required as following is also working

find ./* -prune -name "*.c"

./file1.c
./file2.c
./file3.c
./file4.c

Kindly correct if I am wrong.

You are right.

-type f will make sure that find command returns only regular files in the output. I think it is a good practice to specify this option if you are looking only for regular files.

Any idea how to we do same job by using GREP?
Reason for request: Just wana check how grep behave?

Thanks in advance,

Using grep :

find . -name "*.c" | grep -E '^\.\/[a-zA-Z0-9_-]+\.c'

Using awk :

find . -name "*.c" | awk -F"/" 'NF==2'

But find without -prune option is going to be slower because it has to descend into each sub-directories and search files.

So I don't recommend using these commands.

How about

ls | grep '.*\.c$'

If you don't want to descend into subdirectories, the simple way to do this is:

ls -1 *.c

Note that in the ls option -1 that is the digit one, not the letter ell.
Or, if you just want to see how pruning would work using a basic regular expression in grep instead of a filename pattern match in the shell, use:

ls|grep '[.]c$'

If you wonder why the $ is there, try running the above command with and without the $ in a directory in which there is a file named source.cpp and a file named source.c .

If you wonder why you need [.] instead of just . in a BRE, try the command above with and without the $ and with and without the square brackets in a directory that contains the files named before and files named abc , bcd , and c .

Namely

find . -maxdepth 1 -name "*.c"

Unix find with a "." startdir:

find . \! -name . -prune -name "*.c" -print

grep:

\ls | grep '[.]c$'

If the number of files is not too high, you can try:

printf "%s\n" *.c
echo *.c