I have a folder which has some text files and other folders in it which in turn have more text files in them. I need a command which will recursively loop over the folder and clear all the contents from all the files present in that directory and its subdirectories.

How do I do this?


You can do this with find:

cd top_level_dir
find . -type f -exec bash -c "echo -n '' > {}" \;

For every filename it invokes Bash (not very efficient) and echos, without newline because of the -n, essentially nothing to the file, thereby overwriting its contents and creating a zero length file.

If you have a lot of files and/or have to this often a small (C/Python/Perl/Ruby) utility that reads from input a list of NUL terminated filenames and writes zero bytes to each of them would spead things up considerably ( find -type f -print0 | your_zeroing_util )

You can e.g. use the following as your_zeroing_util:

#!/usr/bin/env python

import sys

inp = sys.stdin.read()
while inp:
   if '\0' in inp:
      file_name, inp = inp.split('\0', 1)
      # print("emptying [{}]".format(file_name))
      with open(file_name, 'w') as fp:
   inp += sys.stdin.read()
  • wipe (packaged for debian at least, or available from lambda-diode.com/software/wipe) is also good if you need to securely erase the files so they can't be recovered. Note that copy-on-write (COW) filesystems like btrfs or zfs (or qcow2 disk image files used by VMs) make it extremely difficult to securely erase files. – cas Apr 21 '16 at 12:05

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.