#!/usr/bin/perl

#/****************************************************************************\
#| |
#| Bryce Alcock |
#| This Script will read each line a file, and will conditionally do the |
#| following: |
#| If the line starts with $ARGV[1] (the second argument). |
#| it will print the line as is, and then it will |
#| copy the line replacing all occurances of $ARGV[1] with $ARGV[2]. |
#| If the line does not start with $ARGV[1], it will print the line. |
#| |
#| Example: |
#| |
#| MatchDupReplace.pl inputFile.txt YY XY |
#| |
#| inputFile.txt: |
#| |
#| YY banana YY Apple YY YC. |
#| YP banana YP Apple YY YD. |
#| |
#| OUTPUT: |
#| |
#| YY banana YY Apple YY YC. |
#| XY banana XY Apple XY YC. |
#| YP banana YP Apple YY YD. |
#| |
#| WHAT IS THIS GOOD FOR: |
#| I use this to conditionally double the number and variety of input |
#| lines for various load test scripts. |
#| |
#| This can also be used as a building block for more complex replacement |
#| Conditionals. |
#\****************************************************************************/


# ARGV[0] is the file we are processing.
$File = $ARGV[0];
# Keep track of the number of lines read in,
# and the number of lines printed out.
$linesIN = 0;
$linesOUT = 0;

# ARGV[1] is the pattern to match.
# ARGV[2] is the replacement string.
$pattern=$ARGV[1];
$replacement=$ARGV[2];

open(FILE,"+< $File");
$out='';
while($line =<FILE>){
$linesIN++;
# NOTE: that the ^ means the line will only match if $pattern
# is at the front of the $line.
if($line =~ /^$pattern/){
$linesOUT+=2;
# print the original line.
print "$line";
# I make a copy of the original here for clarity.
# a more efficeint version would just modify in place.
$newline = $line;
$newline =~ s/$pattern/$replacement/g;
# print the modified line.
print "$newline";
}else{
$linesOUT+=1;
print "$line";
}
}
print "\n\n\tLines IN: $linesIN linesOUT $linesOUT!\n";
close(FILE) or die "can't close $File $!";