Bash: How to Remove All Whitespaces from File


Often you may want to use Bash to remove all whitespaces from a file.

You can use the following basic syntax to do so:

sed -i '/^$/d;s/[[:blank:]]//g' team_names.txt

This particular example will remove all whitespaces from the file named team_names.txt.

Here is what the various sed commands do:

  • -i: Specifies that the file should be modified in-place
  • s: Used to substitute one pattern for another
  • [[:blank:]]: Specifies that all blanks should be substituted
  • g: Specifies that substitutions should be made “globally”, i.e. all blanks should be replaced

Since we don’t specify a replacement pattern to use, sed replaces all whitespace with nothing, which effectively removes all whitespaces from the file.

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

Example: Use Bash to Remove All Whitespace from 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:

Notice that there are several leading and trailing whitespaces in various lines in the file.

Suppose that we would like to remove all whitespaces from each line in the file.

We can use the following syntax to do so:

sed -i '/^$/d;s/[[:blank:]]//g' team_names.txt

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

Bash remove all whitespaces from file

Notice that when we view the updated file we can see that all whitespaces have been removed from each line in the file.

Related Tutorials

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

Bash: How to Replace Text in String
Bash: How to Replace Space with Underscore
Bash: How to Replace Special Characters in String
Bash: How to Replace Multiple Characters in String

Leave a Reply