How to Use sed to Remove Trailing Whitespaces in File


Often you may want to use sed to remove all trailing whitespaces from each line in a file.

You can use the following basic syntax to do so:

sed -i -e 's/[[:space:]]*$//g' team_names.txt

This particular example will remove all trailing whitespaces from each line in the file named team_names.txt.

Here is what the various sed commands do:

  • -i: Modify the file in-place
  • -e: Specifies that the next expression should be interpreted as a sed command
  • s: Used to substitute one pattern for another
  • [[:space:]]*$: Specifies that all trailing whitespace to the end of the line should be substituted
  • g: Specifies that substitutions should be made “globally”, i.e. all occurrences should be replaced

The following example shows how to use this syntax in practice.

Example: Use sed to Remove Trailing Whitespaces in File

Suppose that we have a file named team_names.txt that contains the names of various basketball teams.

We can use the following syntax to view all lines from this file and display a $ character to show us where each file ends:

sed -n l team_names.txt

The following screenshot shows how to use this syntax in practice:

sed view lines in file with whitespaces

We can see that several lines in the file have trailing whitespaces at the end of the line.

We can use the following syntax to remove the trailing whitespaces from each line:

sed -i -e 's/[[:space:]]*$//g' team_names.txt 

The following screenshot shows how to use this syntax in practice:

sed remove trailing whitespaces

Notice that when we view the contents of the file again we can see that all trailing whitespaces at the end of each line have been removed.

Related Tutorials

The following tutorials explain how to perform other common tasks in sed:

How to Use sed to Print Out Line Numbers
How to Use sed to Print Specific Lines in File
How to Use sed to Print Every nth Line of File
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply