Sunday, December 30, 2012

Replace Words in a file based upon another configuration file

This interesting question was asked in a quiz in one of the competitions in the place where i work:

Input file-1

Hello HELLO
world WORLD
good GOOD



Input file-2

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 input file then they should be replace with waht 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"}' input_file1 input_file2

Yes,its a one liner.
I would explain the solution once if i have any comments.

No comments:

Post a Comment