1 | #!/usr/bin/perl |
---|
2 | eval "exec /usr/local/bin/perl -S $0 $*" |
---|
3 | if $running_under_some_shell; |
---|
4 | |
---|
5 | require 'getopts.pl'; |
---|
6 | &Getopts("p:vh"); # help, pattern file, verbose, |
---|
7 | |
---|
8 | if ($opt_h || ! $opt_p) { |
---|
9 | print STDERR <<NO_MORE_HELP; |
---|
10 | word-replace |
---|
11 | |
---|
12 | Replace *words* with patterns. Pattern file specifies which patterns |
---|
13 | to replace on each line. All patterns are wrapped with perl \\b regexp |
---|
14 | specifiers. |
---|
15 | |
---|
16 | Usage: $0 [-v] -p pattern-file files to replace |
---|
17 | |
---|
18 | -v -- possibly more verbose |
---|
19 | -p file -- pattern file |
---|
20 | -h -- help |
---|
21 | |
---|
22 | anything else == this help message |
---|
23 | |
---|
24 | Pattern file looks like this: |
---|
25 | |
---|
26 | # Example: |
---|
27 | # ignores all lines with beginning with # or not exactly 2 fields |
---|
28 | _Dorky_Name rtems_dorky_name # comments, and blank lines are cool |
---|
29 | _Dorky_Name2 rtems_dorky_name2 # comments, and blank lines are cool |
---|
30 | NO_MORE_HELP |
---|
31 | exit 0; |
---|
32 | } |
---|
33 | |
---|
34 | $verbose = $opt_v; |
---|
35 | $pattern_file = $opt_p; |
---|
36 | |
---|
37 | # make standard outputs unbuffered (so the '.'s come out ok) |
---|
38 | $oldfh = select(STDERR); $| = 1; select($oldfh); |
---|
39 | $oldfh = select(STDOUT); $| = 1; select($oldfh); |
---|
40 | |
---|
41 | # pull in the patterns |
---|
42 | open(PATTERNS, "<$pattern_file") || |
---|
43 | die "could not open $pattern_file: $!, crapped out at"; |
---|
44 | |
---|
45 | foreach (<PATTERNS>) |
---|
46 | { |
---|
47 | chop; |
---|
48 | s/#.*//; |
---|
49 | next if /^$/; |
---|
50 | ($orig, $new, $junk, @rest) = split; |
---|
51 | next if ( ! $orig || ! $new || $junk); # <2 or >2 patterns |
---|
52 | die "pattern appears 2x: '$orig' in '$pattern_file'--" if defined($patterns{$orig}); |
---|
53 | $patterns{$orig} = $new; |
---|
54 | } |
---|
55 | close PATTERNS; |
---|
56 | |
---|
57 | # walk thru each line in each file |
---|
58 | foreach $file (@ARGV) |
---|
59 | { |
---|
60 | print "$file\t"; |
---|
61 | |
---|
62 | open (INFILE, "<$file") || |
---|
63 | die "could not open input file $file: $!"; |
---|
64 | |
---|
65 | $outfile = $file . ".fixed";; |
---|
66 | open (OUTFILE, ">$outfile") || |
---|
67 | die "could not open output file $outfile: $!"; |
---|
68 | |
---|
69 | while (<INFILE>) |
---|
70 | { |
---|
71 | study; # maybe make s/// faster |
---|
72 | foreach $key (keys %patterns) |
---|
73 | { |
---|
74 | if ( s/\b$key\b/$patterns{$key}/ge ) |
---|
75 | { |
---|
76 | print "."; |
---|
77 | } |
---|
78 | } |
---|
79 | print OUTFILE $_; |
---|
80 | } |
---|
81 | print "\n"; |
---|
82 | close INFILE; |
---|
83 | close OUTFILE; |
---|
84 | } |
---|
85 | |
---|