inprogress
[jalview.git] / forester / ruby / scripts / replace.rb
1 #!/usr/local/bin/ruby -w
2 #
3 # = replace 
4 #
5 # Copyright::  Copyright (C) 2006-2008 Christian M. Zmasek
6 # License::    GNU Lesser General Public License (LGPL)
7 #
8 # $Id: replace.rb,v 1.5 2008/08/28 17:09:07 cmzmasek Exp $
9 #
10 # To replace multiple strings in file.
11 # Map file contains intructions for replacement (one on each line)
12 # in the following format (by example): old#new
13 #
14
15
16 module ForesterScripts
17     
18     if RUBY_VERSION !~ /1.9/
19                       puts( "Your ruby version is #{RUBY_VERSION}, expected 1.9.x " )
20                       exit( -1 )
21                 end     
22     
23     if ( ARGV == nil || ARGV.length != 3 )
24         puts( "usage: replace.rb <map-file> <infile> <outfile>" )         
25         exit( -1 )
26     end    
27     mapfile = ARGV[ 0 ]
28     infile  = ARGV[ 1 ]
29     outfile = ARGV[ 2 ]
30     
31     
32     if ( File.exists?( outfile ) ) 
33         puts( "outfile [" + outfile + "] already exists" )
34         exit( -1 )  
35     end
36     if ( !File.exists?( infile) )
37         puts( "infile [" + infile + "] does not exist" )
38         exit( -1 ) 
39     end 
40     if ( !File.exists?( mapfile ) ) 
41         puts( "mapfile [" + mapfile + "] does not exist" )
42         exit( -1 ) 
43     end                
44     
45     old_new_map = Hash.new
46     
47     File.open( mapfile ) do | file |
48         while line = file.gets
49             if ( line =~/(\S+)\s*#\s*(\S+)/ )
50                 old_new_map[ $1 ] = $2      
51                 puts( $1 + ' => ' + $2 )     
52             end
53         end
54     end 
55     
56     if ( old_new_map.size < 1 ) 
57         puts( "mapping file was empty" )         
58         exit( -1 )    
59     end   
60     
61     data_str = String.new
62     
63     File.open( infile ) do | file |
64         while line = file.gets
65             data_str =  data_str + line.chomp
66         end 
67     end     
68     
69     old_new_map.each_pair{ |old, new|
70         data_str = data_str.gsub( old, new )
71     }
72     
73     open( outfile, 'w' ) do |file|
74         file.write( data_str )
75     end      
76     
77     puts( "wrote " + outfile )
78     
79 end
80
81