Small scripts

posted Tue, 11 Oct 2005 21:24:00 GMT by Jonas Bengtsson

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!"

Comments One comment

Comments

  1. Avatar replica rolex said 1496 days later:
    $75 Replica Rolex Watches sale, Our site provides Rolex replica, replica Rolex Watches, replica breitling, replica Cartier, replica Omega, Tag Heuer Watches. . .more than 100 famous rolex brands" rolex air king rolex datejust rolex day date rolex daytona rolex gmt rolex submariner rolex yachtmaster a lange sohne watches alain silberstein watches bell ross watches breguet watches breitling watches bvlgari watches cartier watches omega watches patek philippe watches

Respond

This is where you come in. Please leave a comment whether you agree, disagree or none of the above.

(required)

(to your blog or homepage)

(won't be shown nor shared)


  Preview