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.

7 Answers 7

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.

2
  • 1
    The one in the loop creates a file called {FILE}. The first quotation mark needs to go before the dollar sign instead of after. Sep 9, 2009 at 16:09
  • Gak! Typo fixed.
    – kmarsh
    Sep 9, 2009 at 17:43
3

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

find . -name "*.log" -exec sh -c ">{}" \;
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)

1
for i in *.log; do cp /dev/null $i; done

Or, if you want to recurse:

find . -name "*.log" -exec cp /dev/null {} \;
2
  • 1
    you miss a ". ( 15 chars here :) )
    – drAlberT
    Sep 9, 2009 at 15:52
  • 1
    after log Sep 9, 2009 at 16:11
0

A loop could do:

for i in *.log; do echo "" > $i; done
1
  • 5
    We should be using echo with the -n flag to prevent putting a useless \n at the top of the file. Sep 9, 2009 at 15:18
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.

-1

This will also work.

find *.txt | awk '{print " " > $1}'

You must log in to answer this question.

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