A.Walid
A.Walid

Reputation: 37

shell script that allows to empty a file when it exceeds a certain size

I'm looking for a Linux script that allows to empty the contents of a file when it exceeds a certain size for example 50 kB.

I tried this script :

#!/bin/bash
find /home/walid/Documents -type f -size +50k -exec echo >"{}" \;

but it does not work.

On the other hand it works well for deleting files:

#!/bin/bash
find /home/walid/Documents -type f -size +50k -exec rm "{}" \;

Upvotes: 1

Views: 726

Answers (3)

nbari
nbari

Reputation: 26925

Give a try to this:

find /home/walid/Documents -type f -size +50k -exec cp /dev/null {} \;

That should work in any *nix like operating system, but also you could give a try to truncate -s 0 filename

find /home/walid/Documents -type f -size +50k -exec truncate -s 0 {} \;

Upvotes: 0

zevoid
zevoid

Reputation: 171

A little tweak on your first script should work fine:

#!/bin/bash
find /home/walid/Documents -type f -size +50k -exec sh -c 'echo -n > {}' \;

Upvotes: 0

Alfe
Alfe

Reputation: 59426

Your redirection (>) takes place before starting find. You probably now have a file of name {}.

I propose to use truncate instead of a redirection for overwriting the file:

find /home/walid/Documents -type f -size +50k -exec truncate --size 0 "{}" \;

Upvotes: 1

Related Questions