How to empty all files in a directory

Hi all,

Can you tell me how to empty all files in a directory with a "find" command?

It does not seem to work the way I try it:

[root@localhost dir1]# ls -l *.dat
-rw-r--r--    1 root     root            7 Jul 20 20:51 la2.dat
-rw-r--r--    1 root     root            4 Jul 20 20:51 la.dat
[root@localhost dir1]# find /root/dir1 -name "*.dat" -exec touch {} \;
[root@localhost dir1]# ls -l *.dat
-rw-r--r--    1 root     root            7 Jul 20 20:53 la2.dat
-rw-r--r--    1 root     root            4 Jul 20 20:53 la.dat

Thanks

One way -

#!/bin/ksh
find /path/to/files -type f |\
while read file
do 
      > $file
done

Thanks, but I know how to do it with a loop and I was wondering how to do it with "find" and exec.

I usually use this :

 for i in `find ./ -name "*.dat" -type f`; do > $i; done

doesnt use exec, but does it wthout looping

find . -name '*.dat' -type f | xargs rm
find . -name "*.dat" -type f -exec cp /dev/null {} \;

Hello majormark,

for you information, "touch" only change file access and modification times and if file does not exist it will create file. :slight_smile:

  • nilesh

this is going to delete and not empty them

find -exec or xargs require an external command. There is no single standard external command to truncate a file; the cp /dev/null (target) command suggested by reborg is one of the possible ways to do it, or you could create an external command trunc in a shell script:

#!/bin/sh
for f in "$@"; do
  >"$f"
done

This merely masks out the loop from plain view, but if you always invoke it with only one file name argument, the loop isn't necessary (though it's simple enough, and supporting multiple target files is standard practice for shell commands).

Obviously, you could use a Perl script or cp /dev/null "$f" instead of the truncation through redirection.

ah, I misunderstood the "empty directory" bit, ty for clarifying

% print hmm > {1..5}
% head *
==> 1 <==
hmm

==> 2 <==
hmm

==> 3 <==
hmm

==> 4 <==
hmm

==> 5 <==
hmm
% : > *
% ls -l
total 0
-rw-r--r-- 1 radoulov radoulov 0 2008-07-21 22:34 1
-rw-r--r-- 1 radoulov radoulov 0 2008-07-21 22:34 2
-rw-r--r-- 1 radoulov radoulov 0 2008-07-21 22:34 3
-rw-r--r-- 1 radoulov radoulov 0 2008-07-21 22:34 4
-rw-r--r-- 1 radoulov radoulov 0 2008-07-21 22:34 5

This is Z-Shell.

If you insist to use find:

find . \( -name . -o -prune \) -type f -exec sh -c ':> "$1"' - {} \;