« Back to Data processing: Frequently Asked Questions

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:]]*$//' 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 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

Other questions related to Data processing

    Related articles

    Like to learn more? Here is a list of articles within the same category or having similar tags.

    Feedback

    Small picture of Michael Boelen

    This article has been written by our Linux security expert Michael Boelen. With focus on creating high-quality articles and relevant examples, he wants to improve the field of Linux security. No more web full of copy-pasted blog posts.

    Discovered outdated information or have a question? Share your thoughts. Thanks for your contribution!

    Mastodon icon