Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

jack126guy commented Feb 1, 2022

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