Is there a way to use > operator in find -exec

2

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?

Sencer H.

Posted 2014-02-11T14:14:03.447

Reputation: 961

Answers

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

Posted 2014-02-11T14:14:03.447

Reputation: 182 472

1Ouch! My head! How I can't remember that :) Thank you. – Sencer H. – 2014-02-11T14:42:47.793

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)

stib

Posted 2014-02-11T14:14:03.447

Reputation: 3 320

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

Posted 2014-02-11T14:14:03.447

Reputation: 34 501

+1 for being a good solution. Probably not the one the OP was looking for, but very nice to have on the site. – Hennes – 2014-03-08T13:54:04.293

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

Daniel B

Posted 2014-02-11T14:14:03.447

Reputation: 40 502