Categories
Linux

Linux Tip: Truncate multiple files using find

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 replies on “Linux Tip: Truncate multiple files using find”

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

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 to PM Cancel reply

Your email address will not be published. Required fields are marked *