I'd like to find and delete all core files in some large directory tree.

To do this, I'd like to match files that satisfy a particular file name pattern, like:

find . -name 'core*'

... but once such a file is found, I also want to run the file command on it to make sure it's really a core dump, something like:

file --brief --mime <filename> | grep -q 'application/x-coredump'

If that command succeeds, I'd like to delete the file. Can I do it all within find?

It's important that the behavior is "shortcut": I don't want to run file unless the command matches the pattern, since that would be very slow.


find + bash approach:

find / -type f -name "*core*" -exec bash -c \
'[[ `file -bi "$0"` =~ application/x-coredump ]] && echo rm "$0"' {} \;

Remove echo call if you convinced of found "needed" filenames.

Or even shorter - with find's -delete action:

 find / -type f -name "*core*" -exec bash -c \
'[[ `file -bi "$0"` =~ application/x-coredump ]]' {} \; -delete

Sure it's possible:

find . -name '*.core' -type f -exec \
    sh 'if file -bi "$1" | grep -qw ^application/x-coredump; then printf "%s\n" "$1"; fi' \
    sh {} \;

If you're happy with the result replace printf "%s\n" by rm -f.

  • Awesome. I'm also curious however if the check be done within find itself? It saves launching the shell and you can use options like -print0 for filename handling. – BeeOnRope Nov 16 '17 at 22:54
  • @BeeOnRope - in order to avoid invoking a shell you'd have to write a program that checks the mimetype of each core* file found and returns success if it's application/x-coredump and failure otherwise; you could then run smth like find . -name '*.core' -exec my_app {} \; -print0 – don_crissti Nov 16 '17 at 23:36
  • @don_crissti - so exec is interpreted as a predicate, per your example: so I could also use the invocation in this answer, but remove the then printf part and move it to -print0? So – BeeOnRope Nov 16 '17 at 23:38
  • 1
    @BeeOnRope - exactly, it's executed only if the previous action (-exec blah-blah) returned true. It's all in the manual... – don_crissti Nov 16 '17 at 23:40
  • stackexchange is my manual :) – BeeOnRope Nov 17 '17 at 21:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.