User Tools

Site Tools


substitute.pl

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

substitute.pl [2019/11/11 22:33] (current)
hyjeong created
Line 1: Line 1:
 +  #​!/​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: 2019/11/11 22:33 by hyjeong