5

What is the best way how to empty a bunch of files in bash? As far I've been doing this

echo "" > development.log
echo "" > production.log

I don't really want to delete those files, so rm is not possible. I've tried many things like

echo "" > *.log

but nothing worked.

Jakub Arnold
  • 1,744
  • 10
  • 26
  • 33

7 Answers7

11

You don't need the echo. Just

>filename

will empty the file. To edit rassie...

for FILE in *.log
do
   >"${FILE}"
done

The quotes and brackets are preferred, as they will correctly handle files with spaces or special characters in them.

kmarsh
  • 3,103
  • 16
  • 22
3

Just for fun, another variation combining Eric Dennis' find with everybody else's redirection:

find . -name "*.log" -exec sh -c ">{}" \;
Dennis Williamson
  • 62,149
  • 16
  • 116
  • 151
1
for i in *.log; do > $i; done

Note that if you really want the files to be emptied you have to use no echo at all, see above, or pass echo the -n flag (echo -n)

drAlberT
  • 10,949
  • 7
  • 39
  • 52
1
for i in *.log; do cp /dev/null $i; done

Or, if you want to recurse:

find . -name "*.log" -exec cp /dev/null {} \;
Eric Dennis
  • 388
  • 1
  • 2
  • 7
0

Solution:

echo -n | tee *.log

Explanation:

echo -n echoes an empty string to stdout; while tee *.log writes stdout to mutiple files with widecard like you wished.

AK_
  • 133
  • 9
0

A loop could do:

for i in *.log; do echo "" > $i; done
-1

This will also work.

find *.txt | awk '{print " " > $1}'
Michael Hampton
  • 244,070
  • 43
  • 506
  • 972