Small scripts
First I wrote a Perl stdin-parsing oneliner yesterday for summing up the output from grep -c:
perl -e "my($sum) = 0; while(<STDIN>) { $sum += $1 if $_ =~ /^[^:]+:(\d+)$/ } print $sum;"And while the syntax is still a bit weird to me I’m starting to like Perl a bit. Did I just say that? I blame the Perlisms in Ruby! At least it solves the problems it’s designed for in a good way.
I also needed a little script to replace all .html files on my old blog with a “I’ve moved” notice. So I wrote the little Python script below (I added some error checking today to make it easier to use). It’s super simple and hence a little embarrassing to post, but perhaps someone will need it some day (at least it will be easy for me to find). And that I wrote it in Python is a bit embarassing as well since I need to start using Ruby for these kinds of tasks.
Use at your own risk!
"""Replaces all files in a directory (and its subdirectories) with one file.
Usage: replacefiles.py SOURCEFILE DESTINATIONDIRECTORY"""
import sys, os.path, shutil
def replace_files_with_file(sourceFile, destinationDirectory, dryrun):
os.path.walk(destinationDirectory, replace_directory, (dryrun, sourceFile))
def replace_directory(arg, dirname, names):
dryrun, sourceFile = arg
for name in names:
name = os.path.join(dirname, name)
if os.path.isdir(name):
continue
if dryrun:
print "copy %(sourceFile)s %(name)s" % vars()
else:
shutil.copyfile(sourceFile, name)
def exit_print_help(help):
print help
sys.exit(-1)
if __name__ == '__main__':
if len(sys.argv) != 3:
exit_print_help(__doc__)
script, source, destination = sys.argv
if not (os.path.isfile(source) and os.path.isdir(destination)):
exit_print_help(__doc__)
print "First a dry run. The following would happen when replacing all files in '%(destination)s' with '%(source)s':" % vars()
replace_files_with_file(source, destination, True)
if raw_input("Are you sure you want to do the actions listed above? [y/n] ")[0].lower() == 'y':
replace_files_with_file(source, destination, False)
print "Done!"
Zero comments