Linux Tip: Truncate multiple files using find

6 January 2011 by , 6 Comments

Assuming you have a find command of

find . -type f -name '*.log'

Then it’s as simple as:

for item in $(find . -type f -name '*.log' ) ;do cat /dev/null > $item ;done

Handy for truncating log files…

6 Responses to “Linux Tip: Truncate multiple files using find”

  1. Rao 2 November 2012 at 10:29 am #

    Thanks for the tip, saved my time.

  2. PM 22 January 2013 at 11:26 am #

    Great tip, thanks.

  3. Sanjay K 2 July 2013 at 6:32 am #

    Good one 🙂

  4. cfit 18 December 2013 at 10:05 pm #

    Hard to find the answer on search engines. They all think I’m looking for zero byte files. Great when I found this! I trimmed it a bit though by removing the superfluous “cat /dev/null” :

    for CleanUp in $(find / -type f -name known_hosts ) ; do > $CleanUp ; done

    • mihafiz 19 January 2015 at 4:35 am #

      Thanks! Exactly what I was looking for.

  5. Henri Schomäcker 20 August 2015 at 3:44 pm #

    Do not use for i in `find …`; do… to handle files found with find because you’ll get in trouble with files with spaces in their filenames.

    Use something like this:
    find /var/log -type f -exec truncate -s 0 {} \;

    To cleanup the whole /var/log directory I use these few lines:

    CMD_FIND=”/usr/bin/find”

    $CMD_FIND /var/log -type f -name ‘*.gz’ -exec rm -f ‘{}’ \;
    $CMD_FIND /var/log -type f -name ‘*.[0-9]*’ -exec rm -f ‘{}’ \;
    $CMD_FIND /var/log -type f -exec truncate -s 0 {} \;

    Yours Henri


Leave a Reply