Last active
February 1, 2022 16:01
-
-
Save jack126guy/c0e27d75f68bb362a2e4 to your computer and use it in GitHub Desktop.
Remove trailing whitespace
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 | |
#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', $_); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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