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?
#!/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:
shopt -s globstar; for file in /var/log/apache2/**.log; do : > "$file"; done
find /var/log/apache2 -type f -name "*.log" -exec sh -c 'for f; do : > "$f"; done' _ {} +
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
$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With