noobcoder noobcoder - 1 year ago 69
Linux Question

Better way of using the redirection symbol in conjunction with find -exec

My goal is to empty every file in a directory. I DON'T want to actually delete the file, I just want to delete it's contents.

If you want to do this with a single file you can do

> file.txt

If I want to run this operation on every file in a directory I can do this:

find . -exec /bin/bash -c '> {}' \;

Notice how the above command has to call
. This is because simply running the command like this,
find . -exec > {} \;
find: invalid argument ;' to -exec'
I suspect this is because the redirection symbol is confusing the command.

I would like to run this command without needing to run

How can this be done?

Answer Source

One easy way to do this is by using truncate:

find -type f -exec truncate -s0 {} +

If you want to only use bash, you could use a while loop:

find -type f -print0 |
    while IFS= read -r -d '' file; do
        > "$file"

Finally, if you didn't mind using bash -c, it would be better to do it as follows to avoid calling bash so many times:

find -type f -exec bash -c 'for file; do > $file; done' - {} +

although I don't like that solution.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download