Manuel Pégourié-Gonnard | 3385cf4 | 2015-04-02 17:59:30 +0100 | [diff] [blame] | 1 | #!/usr/bin/perl |
| 2 | |
| 3 | use warnings; |
| 4 | use strict; |
| 5 | |
| 6 | use utf8; |
| 7 | use open qw(:std utf8); |
| 8 | |
| 9 | # apply substitutions from the table in the first arg to files |
| 10 | # expected usage: via invoke-rename.pl |
| 11 | |
Manuel Pégourié-Gonnard | 88323c7 | 2015-04-03 14:38:02 +0200 | [diff] [blame^] | 12 | my $do_strings = 0; |
| 13 | if( $ARGV[0] eq "-s" ) { |
| 14 | shift; |
| 15 | $do_strings = 1; |
| 16 | } |
| 17 | |
| 18 | die "Usage: $0 [-s] names-file [filenames...]\n" if( @ARGV < 1 or ! -r $ARGV[0] ); |
Manuel Pégourié-Gonnard | 3385cf4 | 2015-04-02 17:59:30 +0100 | [diff] [blame] | 19 | |
| 20 | open my $nfh, '<', shift or die; |
| 21 | my @names = <$nfh>; |
| 22 | close $nfh or die; |
| 23 | |
| 24 | my %subst; |
| 25 | for my $name (@names) { |
| 26 | chomp $name; |
| 27 | my ($old, $new) = split / /, $name; |
| 28 | $subst{$old} = $new; |
| 29 | } |
| 30 | |
| 31 | my $string = qr/".*?(?<!\\)"/; |
| 32 | my $space = qr/\s+/; |
| 33 | my $idnum = qr/[a-zA-Z0-9_]+/; |
| 34 | my $symbols = qr/[!#%&'()*+,-.:;<=>?@^_`{|}~\$\/\[\\\]]+|"/; |
| 35 | |
Manuel Pégourié-Gonnard | 88323c7 | 2015-04-03 14:38:02 +0200 | [diff] [blame^] | 36 | # if we replace inside strings, we don't consider them a token |
| 37 | my $token = $do_strings ? qr/$space|$idnum|$symbols/ |
| 38 | : qr/$string|$space|$idnum|$symbols/; |
| 39 | |
Manuel Pégourié-Gonnard | 3385cf4 | 2015-04-02 17:59:30 +0100 | [diff] [blame] | 40 | my %warnings; |
| 41 | |
| 42 | while( my $filename = shift ) |
| 43 | { |
| 44 | print STDERR "$filename... "; |
| 45 | if( -d $filename ) { print STDERR "skip (directory)"; next } |
| 46 | |
| 47 | open my $rfh, '<', $filename or die; |
| 48 | my @lines = <$rfh>; |
| 49 | close $rfh or die; |
| 50 | |
| 51 | my @out; |
| 52 | for my $line (@lines) { |
Manuel Pégourié-Gonnard | 88323c7 | 2015-04-03 14:38:02 +0200 | [diff] [blame^] | 53 | my @words = ($line =~ /$token/g); |
Manuel Pégourié-Gonnard | 3385cf4 | 2015-04-02 17:59:30 +0100 | [diff] [blame] | 54 | my $checkline = join '', @words; |
| 55 | if( $checkline eq $line ) { |
| 56 | my @new = map { exists $subst{$_} ? $subst{$_} : $_ } @words; |
| 57 | push( @out, join '', @new ); |
| 58 | } else { |
| 59 | $warnings{$filename} = [] unless $warnings{$filename}; |
| 60 | push @{ $warnings{$filename} }, $line; |
| 61 | push( @out, $line ); |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | open my $wfh, '>', $filename or die; |
| 66 | print $wfh $_ for @out; |
| 67 | close $wfh or die; |
| 68 | print STDERR "done\n"; |
| 69 | } |
| 70 | |
| 71 | if( %warnings ) { |
| 72 | print "\nWarning: lines skipped due to unexpected charaacters:\n"; |
| 73 | for my $filename (sort keys %warnings) { |
| 74 | print "in $filename:\n"; |
| 75 | print for @{ $warnings{$filename} }; |
| 76 | } |
| 77 | } |