Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively delete all binary files in folder

I want to recursively delete all binary files in a folder under linux using the command-line or a bash script. I found

grep -r -m 1 "^"  path/to/folder | grep "^Binary file"

to list all binary files in path/to/folder at How to list all binary file extensions within a directory tree?. I would now like to delete all these files. I could do

grep -r -m 1 "^"  path/to/folder | grep "^Binary file" | xargs rm

but that is rather fishy as it also tries to delete the files 'Binary', 'file', and 'matches' as in

rm: cannot remove ‘Binary’: No such file or directory
rm: cannot remove ‘file’: No such file or directory
rm: cannot remove ‘matches’: No such file or directory

The question is thus how do I delete those files correctly ?

like image 819
Christian Avatar asked Oct 17 '25 19:10

Christian


1 Answers

This command will return all binary executable files recursively within a directory, run this first to ensure proper output.

find . -type f -executable -exec sh -c "file -i '{}' | grep -q 'x-executable; charset=binary'" \; -print

If that works you can pass the output to xargs to delete these files.

find . -type f -executable -exec sh -c "file -i '{}' | grep -q 'x-executable; charset=binary'" \; -print | xargs rm -f

Hope this helped, have an awesome day! :)

like image 172
vesche Avatar answered Oct 20 '25 08:10

vesche



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!