#!/user/bin/perl use strict; # use warnings; # SETUP THE FILES FOR THIS DEMO ##################################################### # Define the working directory for files my $dir = 'c:/Documents and Settings/myname/Desktop/'; # Define the filename to put OP's input my $infilename = 'TestCase.txt'; # Define the filename to write the results into my $outfilename = 'TestCaseOut.txt'; # Create the full-path filenames for input and output my $infile = $dir . $infilename; my $outfile = $dir . $outfilename; open(INFILE,"<",$infile) || die "Can't open input file $infilename: $!\n"; open(OUTFILE,">",$outfile) || die "Can't open output file $outfilename: $!\n"; #################################################### # PROCESS THE INPUT my $line = ""; # Initialize variable to hold each line # read in from the input file my $prior_line = ""; # Initialize variable to hold the # previous line (will need for the # swap if need to do the swap # Process each line as it is read in, always keeping track # of previous line (in case need to do a swap foreach $line (){ chomp($line); # remove the trailing '\n' new-line # Per OP's strategy, check to see if the prior line was # a 'fixed-address' entry...using a regex if($prior_line =~ /^fixed-address/){ # if the prior line was, indeed a 'fixed-address' then # check to see if this line is a 'hardware ethernet', # if it is then do the OP's swap using Perl's # ability to do the swap in-place ($line,$prior_line) = ($prior_line,$line) if($line =~ /^hardware ethernet/); } # I write the output to the output file on each # iteration, but since I am effectively doing a sort of # look-ahead one line at a time, I only write the line # that I'm finished with...i.e., the $prior_line print OUTFILE "$prior_line","\n"; # Now, remember the line I just read in so that it # becomes the $prior_line $prior_line = $line; } # When I've read in and processed the entire file, I # have written out all of the lines except the last one # I read in...which the above loop just moved into # $prior_line. So I need to write it out to the output # file to complete the effort. print OUTFILE "$prior_line","\n"; exit(0); #### # Host 1 host 45583 { filename "junk1.cm"; hardware ethernet 11:42:a3:d4:55:83; fixed-address 10.100.34.114; } # Host 2 host D78C3 { filename "junk5.cm"; hardware ethernet 11:42:a3:FD:78:C3; fixed-address 10.100.34.117; } # Host 3 host 3A684 { filename "junk6.cm"; hardware ethernet 11:42:a3:13:a6:84; fixed-address 10.100.34.119; } # Host 4 host 46d54 { filename "junk4.cm"; hardware ethernet 23:10:3d:14:6d:54; fixed-address 10.100.34.120; }