Skip to content

Instantly share code, notes, and snippets.

@jack126guy
Last active February 1, 2022 16:01
Show Gist options
  • Save jack126guy/c0e27d75f68bb362a2e4 to your computer and use it in GitHub Desktop.
Save jack126guy/c0e27d75f68bb362a2e4 to your computer and use it in GitHub Desktop.
Remove trailing whitespace
#!/usr/bin/perl
#This does not read the file from standard input; rather, it processes a list of files, one per line, from standard input.
#This script is in the public domain (http://creativecommons.org/publicdomain/zero/1.0/)
use strict;
use feature 'unicode_strings';
use File::Copy 'move';
while(<STDIN>) {
chomp;
print 'Processing ', $_, "\n";
my ($SOURCEFILE, $NEWSOURCE);
if(!open($SOURCEFILE, '<:encoding(UTF-8)', $_)) {
warn 'Could not open ' . $_ . ': ' . $!;
next;
}
if(!open($NEWSOURCE, '>:encoding(UTF-8)', $_ . '.new')) {
warn 'Could not open ' . $_ . '.new: '. $!;
next;
}
while(local $_ = <$SOURCEFILE>) {
s/\s*$//;
print $NEWSOURCE $_, "\n";
}
warn 'Could not close ' . $_ . ': ' . $! unless close $SOURCEFILE;
warn 'Could not close ' . $_ . '.new: ' . $! unless close $NEWSOURCE;
next unless unlink $_;
warn 'Could not move ' . $_ . '.new to ' . $_ unless move($_ . '.new', $_);
}
@jack126guy
Copy link
Author

This could be replaced by Unix utilities.

With GNU sed: while read FILE; do sed -i 's/\s*$//' "$FILE"; done

With POSIX sed: while read FILE; do NEW="$FILE.new"; sed 's/[[:space:]]*$//' "$FILE" > "$NEW"; mv "$NEW" "$FILE"; done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment