#!/usr/bin/perl # use strict; use warnings; use Text::CSV; $ARGV[0] or die "Usage: $0 [] ..."; my ( $template_file_name, $templateText, %hash ) = ''; my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 2, }) or die "Cannot use CSV: " . Text::CSV->error_diag(); for my $csvFile (@ARGV) { print "\nProcesing file $csvFile ...\n"; open my $csvfh, '<', $csvFile or die "Unable to open $csvFile: $!"; # Ignore column names in first line my $columnNames = $csv->getline($csvfh); # Get vars from second line my @vars = @{ $csv->getline($csvfh) }; # Process each csv line while ( my $row = $csv->getline($csvfh) ) { next unless @$row; my $templateFN = pop @$row; if ( $template_file_name ne $templateFN ) { $template_file_name = $templateFN; undef $templateText; } # keys: fields from second line; values: fields from csv line @hash{@vars} = @$row; $templateText //= getTemplateText($template_file_name); my $templateTextCopy = $templateText; $templateTextCopy =~ s/$_/$hash{$_}/g for keys %hash; my $ofile_name = $hash{'##rtrname##'} . '.txt'; print "Writing to file: $ofile_name\n"; open my $fh, '>', $ofile_name or die "$ofile_name: $!"; print $fh $templateTextCopy; close $fh; } close $csvfh; } print "\nDone!\n"; sub getTemplateText { my ($template_file_name) = @_; local $/; open my $fh, '<', $template_file_name or die "$template_file_name: $!"; $templateText = <$fh>; close $fh; return $templateText; } #### Location,Router Name,Loopback IP,OSPF Process ID,OSPF Area,Network,Mask,GIG0/0 IP Address,0/0 Subnet Mask,Template ##location##,##rtrname##,##loop0-ip##,##ospf-id##,##ospf-area##,##ospf-network##,##ospf-mask##,##eth00-ip##,##eth00-sm##, Sydney,SYD-RTR-001,192.168.15.1,99,0,172.25.16.0,0.0.0.255,172.25.16.6,255.255.255.0,router