简体   繁体   中英

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 ?

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! :)

I coded a tool, called blobs , that lists runable binaries.

Its readme mentions how to pipe to any other command.

This should do the job, if you are deleting a lot of binrary files in a folder.

 find . -type f -executable | xargs rm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM