In a project we have text files looking 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 it in Perl, the replace() function in the following code, but the real application is written in Java, so the solution needs to be in Java as well.
#!/usr/bin/perl
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) = @_;
# Create R12|R21|R1|R2|R3
# making sure R12 is before R1
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"; # backup with current timestamp
write_file( $file, $data);
}
}
Your help for the Java implementation would be appreciated.