Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I can find the list of files using something like:

find /path/to/files -type f

And I can clear the contents of a single file with any of:

> filename

echo -n > filename

cat /dev/null > filename

You can do something like this with commands that don't involve output redirection:

find /path/to/files -type f -exec file '{}' \;

However this does not work:

find /path/to/files -type f -exec echo -n > '{}' \;

I can't seem to construct a command using find's -exec or | xargs to pipe the file list into one of these commands that will clear the files. How can I do this?

share|improve this question
up vote 2 down vote accepted

find /path/to/files -type f -exec /bin/sh -c "> '{}'" ';' should do what you want; see find(1) for details on how exec works in detail, but this invocation runs the command once, putting the filename where {} is.

You can also tell xargs to only pass a single filename to the command, or use find /path -type f | while read file; do echo -n > "$file"; done to do that at the shell level.

share|improve this answer
    
I was trying something along the lines of your first example however it does not work. See my edit in the original question. – Dave Forgac May 4 '12 at 20:11
    
Sorry, I should have noticed that wouldn't work - I didn't think about it, just copied it from your example. The update shows how to fix that; invoking a single shell command. Using the "| while read file; do" version would also work smoothly. – Daniel Pittman May 4 '12 at 20:15
    
Perfect! Thanks – Dave Forgac May 4 '12 at 20:56

Just for fun, here's another option:

find /path/to/files -type f -exec dd if=/dev/null of={} \;
share|improve this answer
    
Nice! I was trying to think of a way to avoid the redirection. – Dave Forgac May 4 '12 at 22:00
    
This one works! Straightforward approach. – Eduardo B. Sep 29 '14 at 5:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .