-1

Under /tmp/REPORTS I have a hundred files. What I want to do is erase the contents of each file in /tmp/REPORTS (not delete them). So I tried the following, but I get this error:

cp /dev/null /tmp/REPORTS/*

cp: Target /tmp/REPORTS/…..  must be a directory
Usage: cp [-f] [-i] [-p] [-@] f1 f2
      cp [-f] [-i] [-p] [-@] f1 ... fn d1
      cp -r|-R [-H|-L|-P] [-f] [-i] [-p] [-@] d1 ... dn-1 dn

How can I clear the contents of all the files in the directory?

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
maihabunash
  • 1,632
  • 9
  • 34
  • 60

4 Answers4

2

Assuming that you mean you want to truncate the contents of each file, you can do this:

for file in /tmp/REPORTS/*; do > "$file"; done

This will clear the contents of each file in the directory.

As gniourf_gniourf has suggested in the comments above, there is a GNU tool truncate that can do the job for you as well:

truncate --size 0 /tmp/REPORTS/*

This will possibly be quicker than looping through the files manually.

Community
  • 1
  • 1
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
1

The question appears to be asking for what is termed a "secure erase".

While you cannot cp /dev/null, you could get the effect you are asking about using dd. Here is a script to illustrate:

#!/bin/sh
for name in $*
do
    test -h "$name" && continue
    test -f "$name" || continue
    blocks=`ls -s "$name" | awk '{print $1; }'`
    dd if=/dev/zero of="$name" count=$blocks
done

The script

  • checks to ensure that the parameter is a regular file.
  • then it asks for the number of blocks for the file.
  • finally, it uses dd to copy 0's from the special device /dev/zero.

This relies on dd and ls having the same notion of blocksize (which appears to be the case). It also assumes that the filesystem does not reallocate blocks for a given file, i.e., that they can be reliably overwritten in-place. If you want a better guarantee, there are other solutions, e.g., this discussion of Secure Erase in UNIX

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
0


you can use this
for remove

find /tmp/REPORTS/ -type f -name "*.*" -exec rm -rf {} \;

or move them to some where you want for cp

find /tmp/REPORTS/ -type f -name "*.*" -exec cp {} \tmp\{} \;

for mv

find /tmp/REPORTS/ -type f -name "*.*" -exec mv {} \dev\null \;
Soheil
  • 837
  • 8
  • 17
0

Try this instead:

$ find /tmp/REPORTS/ -type f -exec cat /dev/null > {} \;

Or if you have a large number of files, try using \+ instead of \; for a more efficient commandline.

James McPherson
  • 2,476
  • 1
  • 12
  • 16