Home: Perl Programming Help: Regular Expressions:
I Need to replace names from 1 file everytime they occur in another file



jtra00
Novice

Jan 24, 2012, 8:32 AM


Views: 9761
I Need to replace names from 1 file everytime they occur in another file

I have 2 files:

file A
1. rabbit Number one like cookies
2. rat and companies created life
3. apple sauce is good
4. ice is water

File B

Rev_1 like carrot
rev_2 is a scientist best friend
Rev_3 saves Newton
Rev_4 is good for skating

How do I replace 1, 2, 3, 4, by rabbit, rat,apple, and ice in file B.
Thanks


rovf
Veteran

Jan 24, 2012, 9:23 AM


Views: 9756
Re: [jtra00] I Need to replace names from 1 file everytime they occur in another file

Replacement itself is easiest by substitution via regular expression. For example, if $s equals 'abc_3 X Y Z', the statement


Code
$s =~ /3/dogfood/;


changes $s into 'abc_dogfood X Y Z'.

To extract the values you need, from file A, you read it line by line, and use the split function.

The canonical way to store the association between the numbers (2) and keywords (rat) would be to use a hash. Since in your case, the numbers are continuous integers, you could also use an array, depending on what you feel more comfortable with.


jtra00
Novice

Jan 24, 2012, 9:29 AM


Views: 9754
Re: [rovf] I Need to replace names from 1 file everytime they occur in another file

Thank you very much. I have used Perl heavily years (7) ago and stopped. And I am back at it, now I have to relearn it again. I will try what you have suggested. Thanks
John

In Reply To