25

I´d like to empty all files from a directory. I´d tried this:

find myFolderPath/* -exec cat /dev/null > {} ';'

but it does not work. How can I do it?

2 Answers 2

44

You can't use redirection (>) within find -exec directly because it happens before the command runs and creates a file called {}. To get around this you need to do it in a new shell by using sh -c.

Also, note that you don't need to cat /dev/null > file in order to clobber a file. You can simply use > file.

Try this:

find . -type f -exec sh -c '>"{}"' \;
3
  • 2
    I found find . -type f -exec sh -c '>"{}"' \; to be working better.
    – Smile4ever
    Commented Jun 9, 2015 at 11:04
  • Was getting error "sh: -c: line 0: syntax error near unexpected token `('" because of some filenames with special characters, changed the command to find . -type f -exec sh -c '>"{}"' \;
    – Víctor
    Commented Oct 11, 2018 at 8:18
  • Another improvement, according to SC2156, the command should become something like find . -type f -exec sh -c '>"$1"' shell {} \; to prevent special characters in file names from being executed as part of the script
    – Oylex
    Commented Dec 9, 2021 at 21:14
16

This will do what you want:

for f in *; do >$f; done
3
  • I like it, but it breaks when spaces in filename. Commented Apr 28, 2016 at 14:42
  • 1
    How to run this one as sudo ?
    – Bax
    Commented Feb 2, 2018 at 20:04
  • Great solution. Worth noting: you want to ensure that you're in the CORRECT folder when doing this. It will execute on all files in the folder you are currently in.
    – Cepheus
    Commented Jun 22, 2022 at 17:38

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