user10573594
user10573594

Reputation: 141

Find big files and empty them

will the following find big log files (over 1GB) at the /opt directory and empty them?

find /opt/ -type f -size +1G -exec cat > /dev/null {} \;

thank you.

Upvotes: 2

Views: 356

Answers (3)

umläute
umläute

Reputation: 31374

the problem you are facing is that the redirection (>) is a property of the shell, whereas cat doesn't know anything about it.

the simplest solution for your problem is probably just putting the file-emptying into a small wrapper script (it needs to escape the $ with backslashes, in order for the heredoc to not expand $@ and $f but instead write them into the wrapper-script literally).

$ cat >/tmp/wrapper-script.sh  <<'EOL'
#!/bin/sh

for f in "$@"; do
  cat /dev/null > "${f}"
done
EOL

$ chmod +x /tmp/wrapper-script.sh

$ find /opt/ -type f -size +1G -exec /tmp/wrapper-script.sh {} +

the wrapper-script iterates over all files given on the cmdline and empties all of them (note the + specifier in the find invocation).

Upvotes: 1

Mark Setchell
Mark Setchell

Reputation: 208043

If you have GNU coreutils, you can use truncate like this:

find /opt/ -type f -size +1G -exec truncate -s0 {} \;

Upvotes: 3

Philippe
Philippe

Reputation: 26810

This is what's required :

find /opt/ -type f -size +1G -exec cp /dev/null {} \;

The redirection in your code causes cat writing big files into /dev/null.

It may be safer to add a name clause :

find /opt/ -type f -name "*.log" -size +1G -exec cp /dev/null {} \;

Upvotes: 3

Related Questions