Bash – How to remove files which do not end with ā€œ.cā€

bashrmwildcards

I have a directory which contains all the C programs. I have also compiled them at the creation time so as to check my code. There are a lot of programs nearly 100 of them. So I want a BASH script that would check whether the file ends with ".c". If it does then it does not do anything, which if it doesn't then it would remove them. Suppose one of my file name is "Hello.c" then I have named its binary during compile time as "Hello". So can anyone make this script for me?

Best Answer

You can use the -delete flag of find (first test with -ls)

find -not -name "*.c" -delete

If you do not want to use find, but only files in the current directory, you could do

rm !(*.c)

Make sure in bash that with shopt -s extglob the correct globbing is set. Additionally, if you have globstar set (shopt -s globstar), you can act recursively (for bash versions above 4):

rm **/!(*.c)
Related Question