Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-Liner command to empty multiple text files in terminal

Tags:

bash

shell

How would you go about using a single command to empty multiple text files in terminal?

My thought was that you could use something along these lines...:

find /var/log/apache2/*log -exec `echo > '{}'` \;

I know it's simple enough to create a shell script that would easily do that:

echo "#!/bin/sh\n\necho \"\" > \"$1\"" > /usr/local/bin/empty && chmod +x /usr/local/bin/empty

...

find /var/log/apache2/*.log -exec empty {} \;

But is it possible to do this without creating your own script in a similar manner?

like image 249
Highway of Life Avatar asked Dec 02 '22 00:12

Highway of Life


2 Answers

#!/bin/bash

for file in /var/log/apache2/*.log; do
  : > "$file"
done

Or the one-liner version

for file in /var/log/apache2/*.log; do : > "$file"; done

If you need to recurse into subdirs, then you can use the following two options:

Bash 4.X

shopt -s globstar; for file in /var/log/apache2/**.log; do : > "$file"; done

Posix

find /var/log/apache2 -type f -name "*.log" -exec sh -c 'for f; do : > "$f"; done' _ {} +
like image 140
SiegeX Avatar answered Dec 20 '22 08:12

SiegeX


Or use sed:

sed Q -i *

replacing file contents in place by emptiness.

update with explanation

sed can do all kinds of replacements, e.g. using regular expressions:

$ cat /etc/passwd | sed -e s/^[^:]*/USER/

with the pattern saying "substitute anything until : with USER", giving:

USER:x:0:0:root:/root:/bin/bash
USER:x:1:1:daemon:/usr/sbin:/bin/sh
USER:x:2:2:bin:/bin:/bin/sh
etc etc

Adding -i in the mix, sed can edit files in-place, so you probably NEVER want to do this:

$ sed -e s/^[^:]*/USER/ -i /etc/passwd

(Note that on e.g. Mac OS X, you need to put in an extra argument after -i to provide the "backup suffix", which is used to make backups before sed does its magic on your files)

Now the quest is for the shortest sed script to lose all input, which is either d or Q. d would delete all input (and then output nothing), Q would quit immediately (and output nothing). Q is presumably fastest.

Then, the sarnold example would look like:

$ ls -l
-rw-r--r-- 1 sarnold sarnold  10161 2011-12-30 17:47 alternatives.log
-rw-r----- 1 sarnold sarnold  50976 2011-12-30 17:47 auth.log
-rw-r--r-- 1 sarnold sarnold    759 2011-12-30 17:47 boot.log
$ sed Q -i *.log
$ ls -l
-rw-r--r-- 1 sarnold sarnold 0 2011-12-30 17:47 alternatives.log
-rw-r----- 1 sarnold sarnold 0 2011-12-30 17:47 auth.log
-rw-r--r-- 1 sarnold sarnold 0 2011-12-30 17:47 boot.log
$ 
like image 25
mvds Avatar answered Dec 20 '22 07:12

mvds