3

I'm trying to empty lots of files under a certain folder.

>file or cat /dev/null > file or echo "" > file can empty file. find . -type f -exec blahblah {} \; can find files and do something on them.

I tried to use the > operator in find ... -exec but the result is different to what I expected.

Is there a way to use > operator in the find command?

An Dorfer
  • 1,178
Sencer H.
  • 1,390

4 Answers4

4

You can't use it directly, since it will be interpreted as an actual redirection. You have to wrap the call in another shell:

find . -type f -exec sh -c 'cat /dev/null >| $0' {} \;

If sh is Bash, you can also do:

find . -type f -exec sh -c '> $0' {} \;
slhck
  • 235,242
2

Or you could redirect the output of the find command with process substitution:

while IFS= read -r -d '' file
do cat /dev/null > "$file"
done < <(find . type -f print0)
slhck
  • 235,242
stib
  • 4,389
1

parallel allows escaping > as \>:

find . -type f|parallel \>{}

Or just use read:

find . -type f|while read f;do >"$f";done

You don't need -r, -d '', or IFS= unless the paths contain backslashes or newlines or start or end with characters in IFS.

Lri
  • 42,502
  • 8
  • 126
  • 159
1

Alternatively, one could just use the appropriately named truncate command.

Like this:

truncate -s 0 file.blob

The GNU coreutils version of truncate also handles a lot of fascinating things:

SIZE may also be prefixed by one of the following modifying characters: '+' extend by, '-' reduce by, '<' at most, '>' at least, '/' round down to multiple of, '%' round up to multiple of.

An even simpler, although less appropriately “named” method would be

cp /dev/null file.blob
user219095
  • 65,551