Created
April 30, 2012 18:58
-
-
Save jgarzik/2561322 to your computer and use it in GitHub Desktop.
Remove trailing whitespaces; files edited in-place.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl -w | |
use strict; | |
my ($argv_fn); | |
my $bytes_saved = 0; | |
while ($argv_fn = shift @ARGV) { | |
&chomp_file($argv_fn); | |
} | |
printf "%u bytes chomped.\n", $bytes_saved; | |
exit(0); | |
sub chomp_file { | |
my ($fn) = @_; | |
my ($s, $i); | |
my $chomped = 0; | |
# read entire data file into memory | |
open (F, $fn) or die "cannot open $fn: $!\n"; | |
my @data = <F>; | |
close (F); | |
# trim trailing whitespace | |
foreach $i (0 .. $#data) { | |
$s = $data[$i]; | |
if ($s =~ /\s$/) { | |
while (($s) && ($s =~ /\s$/)) { | |
chop $s; | |
$bytes_saved++; | |
} | |
$s .= "\n"; | |
$bytes_saved--; | |
if ($s ne $data[$i]) { | |
$chomped = 1; | |
$data[$i] = $s; | |
} | |
} | |
} | |
# dump data back to disk | |
if ($chomped) { | |
open (F, ">$fn") or die "cannot overwrite $fn: $!\n"; | |
print F @data; | |
close (F); | |
print "$fn modified.\n"; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment