tags:

views:

84

answers:

3

Consider a list of numbers:

1
2
3
17
8
9
23
...etc.

I want to replace these numbers with another number, based on another list:

1001=1
1002=2
1003=3
1004=8
1005=23
1006=9
1007=17

What is the quickest way to do this? (like using regular expression in Notepad++, etc.)

+1  A: 

Put your mappings into an array (or a dictionary, depending on how your numbers are, such that):

map[oldvalue] = newvalue;

Then iterate over the original list and replace, eg:

oldlist = '1\n2\n3\n17'
map = {'1' : '1001', '2': '1002', '3' : '1003', '17' : '1007'}

result = ''
for num in oldlist.split('\n'):
    result += map[num] + '\n'

See it on ideone

Aillyn
+3  A: 

I do this kind of thing in perl -- something like

%replacements = (1=>1001, 2=>1002, 3=>1003 );
while (<>) {
   chomp;
   @nums = split(/ /);
   @outnums = ();
   foreach $n (@nums) {
       $outnums[$#outnums + 1] = $replacements{$n};
   }
   print join(' ', @outnums)."\n";
}

then run

perl scriptname.pl < infile > outfile
Lou Franco
perl is very sexy indeed
thenduks
awk - or any language with associative arrays - also does this easily. In this example, since the keys are numeric, not arbitrary strings, you could even get away with dynamic but non-associative arrays.
Jonathan Leffler
Also, even better would be to read the replacements from a file (presumably an argument to the script). It depends, perhaps, on how often this is going to have to be done. Generating the mapping is the hard part, of course.
Jonathan Leffler
+1  A: 

You don't want a regex since you need to somehow map the numbers to their replacements. Here's a script in Ruby:

Given a file called 'nums' like so:

1
2
3

...and so on...

map = {
  1 => 1000,
  2 => 2000,
  ...etc...
}
results = File.open('output','a')
File.open('nums').readlines.each do |line|
  results.write( map[line.to_i].to_s + "\n" ) if map.has_key?(line.to_i)
end

Run this like: ruby thescript.rb and the file 'output' now has your new number set.

thenduks