Skip to content

Instantly share code, notes, and snippets.

@jgarzik
Created April 30, 2012 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgarzik/2561322 to your computer and use it in GitHub Desktop.
Save jgarzik/2561322 to your computer and use it in GitHub Desktop.
Remove trailing whitespaces; files edited in-place.
#!/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