How to remove trailing whitespace from a file
How to remove trailing whitespace from a file?
Run the sed command to trim any trailing whitespace.
sed -i 's/[[:space:]]*$//' FILETo remove any trailing whitespace from a file, we can use sed. By using in-place editing -i, sed can be provided with a search-and-replace action to filter out whitespace at the end of each line. By replacing it with nothing, it will effectively be removed.
sed -i 's/[[:space:]]*$//' mytextfile.txt
Explanation
- -i = inline file edit
- s/ = search
- [[:space:]]*$ = search one or more occurrences of whitespace just before the end of the line
- // = No text, so any occurrences of the whitespace will be emptied
The [[:space:]] is called a character class and refers to space characters. Normally this includes a tab, vertical tab, form feed, new line, carriage return, and of course a space.
Note: the usage of [[:space:]] may not work on non-Linux systems