It's a bit surprising seeing multiple answers suggesting to use python
for this task, as there's no need to write a multi-line program for this.
Standard Unix tools like sed
, awk
or perl
can achieve this easily straight from the command-line.
e.g anywhere you have perl
(Windows, Mac, Linux) the following should achieve what the OP asked:
perl -i -pe 's/[ \t]+$//;' files...
Explanation of the arguments to perl
:
-i # run the edit "in place" (modify the original file)
-p # implies a loop with a final print over every input line
-e # next arg is the perl expression to apply (to every line)
s/[ \t]$//
is a substitution regex s/FROM/TO/: replace every trailing (end of line) non-empty space (spaces or tabs) with nothing.
Advantages:
Edit:
Newer versions of
perl
support\h
(any horizontal-space character), so the solution becomes even shorter:
perl -i -pe 's/\h+$//;' files...
More generally, if you want to modify any number of files directly from the command line, replacing every appearance of FOO
with BAR
, you may always use this generic template:
perl -i -pe 's/FOO/BAR/' files...