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?

An Dorfer
  • 1,178
  • 2
  • 8
  • 14
Sencer H.
  • 1,290
  • 13
  • 22

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
  • 223,558
  • 70
  • 607
  • 592
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
  • 223,558
  • 70
  • 607
  • 592
stib
  • 4,269
  • 6
  • 27
  • 38
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
  • 40,894
  • 7
  • 119
  • 157
  • +1 for being a good solution. Probably not the one the OP was looking for, but very nice to have on the site. – Hennes Mar 08 '14 at 13:54
  • :-( I just accidentally deleted a ton of work with this, for not reading carefully what this was about. I was just trying to figure out the `find` syntax with any command, so I could later change it to what I want. This `read` command doesn't look dangerous... but it is... shame on me, I'm scavenging for backups now... – pgr Nov 11 '21 at 16:31
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
  • 60,360
  • 9
  • 122
  • 163