The project has text files that look like this:
mv A, R3
mv R2, B
mv R1, R3
mv B, R4
add A, R1
add B, R1
add R1, R2
add R3, R3
add R21, X
add R12, Y
mv X, R2
I need to replace the strings according to the following, but I am looking for a more general solution.
R1 => R2
R2 => R3
R3 => R1
R12 => R21
R21 => R12
I know I could do this in Perl, the replace () function in the following code, but the real application is written in Java, so the solution should be in Java.
use strict;
use warnings;
use File::Slurp qw(read_file write_file);
my %map = (
R1 => 'R2',
R2 => 'R3',
R3 => 'R1',
R12 => 'R21',
R21 => 'R12',
);
replace(\%map, \@ARGV);
sub replace {
my ($map, $files) = @_;
my $regex = join "|",
sort { length($b) <=> length($a) }
keys %$map;
my $ts = time;
foreach my $file (@$files) {
my $data = read_file($file);
$data =~ s/\b($regex)\b/$map{$1}/g;
rename $file, "$file.$ts";
write_file( $file, $data);
}
}
Your help in implementing Java will be appreciated.