#!/usr/bin/perl ############################################################################### # # name: txtSub.pl # # usage: txtSub.pl -th # [ ...] # # decription: substitute text in list of files. # the text contained in will be inserted in all # files, in the place of the text included between the first line # that contains and the first line that contains . # # author: paolo guiducci # # Disclaimer: You are free to use this code, being understood that I decline # any responsibility, direct or implied, for damages or # inconveniences that its use or impossibility of use may cause # (directly or indirectly). If your local law does not allow a full # decline of responsibility by the author of a software that you # use, then you are not allowed to use this code or any part of it. # # web: http://pguiducci.com ############################################################################### use Getopt::Std; getopts("th") or usage(); if ($opt_h || @ARGV < 4) {usage()}; my $str1 = shift(@ARGV); my $str2 = shift(@ARGV); my @fileIn=(); my @fileOut=(); $textFile = shift @ARGV; my $rFileIns=loadText(); confirm(); print "\n\n"; foreach $fileArg (@ARGV) { if (!-w $fileArg) { print "warning: $fileArg doesn't exist or not writable\n"; next; } open(IN, "$fileArg") || print "can't open file $fileArg\n"; @fileIn = ; close IN; $indMax = @fileIn; @fileOut = (); $ind = 0; ### Firt part loop until ($ind >= $indMax || $fileIn[$ind] =~ /$str1/) { push(@fileOut, $fileIn[$ind]); $ind++; } if ($ind >= $indMax) { print "$fileArg --> skipped, 1st string not found!\n"; next; } ### Insert text push(@fileOut, @$rFileIns); ### Skip lines loop until ($ind >= $indMax || $fileIn[$ind] =~ /$str2/) { $ind++; } if ($ind >= $indMax) { print "$fileArg --> changed, 2nd string not found!\n"; next; } $ind++; ### Last part loop until ($ind >= $indMax) { push(@fileOut, $fileIn[$ind]); $ind++ } if ($opt_t) { print "test updated file: $fileArg\n"; print } else { open (OUT, "> $fileArg") or die "unable to open $fileArg in output mode"; print OUT @fileOut; close OUT; print "updated file: $fileArg\n"; } } print "\n"; ################### ### Subroutines ### ################### sub loadText { open(F_TEXT, "$textFile" ) || die "can't open file $textFile" ; my @file = ; close F_TEXT; return \@file; } sub confirm { print "\nlist of files to be changed:\n\n"; foreach $ln (@ARGV) { print " $ln\n" } print "\nfrom string: $str1\n"; print "to string: $str2\n"; print "\ntext to be inserted:\n\n"; foreach $ln (@$rFileIns) { print " $ln" } print "\n"; do { if (!$opt_t) { print "\nreal mode!"; } else { print "\ntest mode"; } print ", confirm? "; chomp ($conf = ); } until ($conf =~ /[yn]/); if ($conf ne "y") { exit; } } sub usage { print "usage txtSub.pl -th [ ... ]\n"; exit; }