User Tools

Site Tools


substitute.pl
#!/usr/bin/perl
# https://stackoverflow.com/questions/12400217/replace-a-field-with-values-specified-in-another-file
# answer by Vijay; later modified by Haeyoung Jeong

use strict;
use warnings;

if ($#ARGV < 1) {
   print STDERR "Usage : $0 <key-value-file> <file-to-be-modified>\n";
   print STDERR "        First file should use tab for the field separator.\n";
   exit;
}

my %hsh=();

open (MYFILE, $ARGV[0]);
open (MYFILE2, $ARGV[1]);

while (<MYFILE>) {
my@arr = split/\s+/;
$hsh{$arr[0]} = $arr[1];
}
my $flag;
while(<MYFILE2>)
{
$flag=0;
my $line=$_;
foreach my $key (keys %hsh)
{
   if($line=~/$key/)
   {
    $flag=1; 
    $line=~s/$key/$hsh{$key}/g;
#    print $line;
   }
}
print $line;
  if($flag!=1)
  {
  print $line;
  $flag=0;
  }
}
close(MYFILE);
close(MYFILE2);
substitute.pl.txt · Last modified: 2021/03/17 13:09 by 127.0.0.1