« Back to Data processing: Frequently Asked Questions

How to remove trailing whitespace from a file

To 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 occurences of whitespace just before the end of the line
  • // = No text, so any occurences 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

Other questions related to Data processing

Feedback

Is the described answer not working or incorrect, got another tip or question? Share your thoughts!