3 # Search and replace params in HTML tags. Change all lines to end with \r\n
5 # Author: Petter Reinholdtsen <pere@td.org.uit.no>
15 print "$0 [-c <configfile>|'<search-replace command>'] <paths>\n";
16 print " -c Change default config-file\n\n";
17 print "Command format: <TAG>.<PARAM> {<from>-><to>|-}\n";
18 print " If <from> is '*', the param will be inserted where necessary.\n";
19 print " If command is '-', the param is removed.\n\n";
22 if (! getopts('c:') || ! @ARGV) {
28 open(CFILE, "<$opt_c") || die "Unable to open $opt_c for reading";
31 push(@commands,msdosChompLine($_));
35 @commands = (shift(@ARGV));
43 return if ( ! /\.s?html?$/i || ! -r "$dir/$_" );
44 $filename = "$dir/$_";
45 print "Prosessing $filename\n";
46 $oldtime = (stat("$filename"))[10]; # save change-time to compare before saveing
47 if (! open(FILE, "<$filename") ) {
48 warn "Unable to open $filename for reading. Nothing changed.";
51 foreach $line (<FILE>) {
53 $line = msdosChompLine($line);
54 foreach $command (@commands) {
55 local($tag, $param, $cmd) = $command =~ m/^(\w+)\.(\w+) (.+)$/;
56 if ( $line =~ /\<$tag[^\>]*\>/i ) {
57 print "L: \"$line\"\nC: $tag $param $cmd\n" if ($debug);
58 if ($cmd eq "-") { # Remove the param
59 $line =~ s/(\<$tag[^\>]*) $param\s*=\s*\"?[^\" ]+\"?([ >])/\1\2/i;
60 } elsif ($cmd =~ /\-\>/) { # change param
61 ($from, $to) = $cmd =~ m/^(.+)-\>(.+)$/;
62 print "$tag.$param $from -> $to\n" if ($debug);
65 m/^(.*\<$tag[^\>]* )($param\s*=\s*\"?)([^\" >]+)(\"?.*)$/i ) {
66 print "Param hit: \"$3\"\n" if ($debug);
67 # param exist - change it
68 if ($from eq '*' || $from eq $3) {
69 $line = "$1\U$2"."$to$4";
70 print "Replaced\n" if ($debug);
72 } elsif ($from eq '*') {
73 # new param in tag - insert it
74 $line =~ m/^(.*\<$tag[^\>]+)(\>.*)$/i;
75 $line = "$1 \U$param=\""."$to\"$2";
76 print "Inserted\n" if ($debug);
77 } # else nothing is done
79 # Pack and remove redundand space inside tags
80 $line =~ s/(\<[^\>]+) \s+([^\>]*>)/\1 \2/;
82 print "L2: \"$line\"\n" if ($debug);
85 push(@newhtml, "$line\r\n");
89 # Save backup and replace
90 if ($oldtime == (stat("$filename"))[10]) { # Not changed while we prossessed
91 print @newhtml if ($debug);
92 local($backupname) = "$filename.backup";##-$$";
93 if (open(BACKUP, ">$backupname") ) {
94 if (print BACKUP @html) { # backup saved - replace original
96 if ( open(FILE, ">$filename") ) {
97 if (print FILE @newhtml) { # Original replaced - all OK
101 warn "Unable to write to $filename. Probably damage - check backup $backupname."
104 warn "Unable to open $filename for writeing. Possible damage! - check backup $backupname";
109 warn "Unable to save backup for $filename. Nothing changed.";
112 warn "Unable to open backupfile $filename for writeing. Nothing changed.";