Compare two files and replace
This was one crazy question asked in a quiz in one of the competitions in the place where I work:They wanted this to be solved using perl only and ASAP. So I came up with a one liner.
File1
Hello HELLO world WORLD good GOODFile2
Hello all this is just a text file to demonstrate some good programming. Welcome to the world of programming.
Now the words of the first column of the first file,if they are present in the second file then they
should be replaced with what ever is there in the second column of the first file.
So the output would look like:
HELLO all this is just a text file to demonstrate some GOOD programming. Welcome to the WORLD of programming.
Below is the solution that i wrote in perl:
perl -F -lane 'BEGIN{$count=0;$flag=0} if($flag==1) {$count=1} $X{$F[0]}=$F[1]; if(eof && $count!=1) {foreach(%X){$H{$_}=$X{$_}}; $flag=1} foreach(@F){if(exists($H{$_})){$_=$H{$_};}} if($count!=0){print "@F"}' File1 File2
0 comments: