How to Remove Spaces from String in Bash (With Examples)


Often you may want to remove spaces from a string in Bash.

There are two common ways to do so:

Method 1: Remove Spaces from String Using sed

echo "$my_string" | sed 's/ //g'

This particular example removes all spaces from the string stored in the variable named my_string.

This method uses the sed command s/ to perform a substitution, replace any space with nothing.

The g command specifies that this should be done “globally”, meaning all spaces should be replaced with nothing.

Method 2: Remove Spaces from String Using tr

echo "$my_string" | tr -d ' '

This particular example removes all spaces from the string stored in the variable named my_string.

This method uses the tr operator, which is used to translate or substitute one pattern for another in Bash.

The -d command specifies that all spaces should simply be deleted from the string.

The following examples show how to use each of these methods in practice.

Example 1: Remove Spaces from String Using sed

Suppose that we have the following string in Bash:

  • ”    A00394BB “

Suppose that we would like to remove all spaces from this string.

We can use the following syntax to do so:

my_string="    A00394BB "
echo "$my_string" | sed 's/ //g'

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

Bash remove spaces from string using sed

This returns the string with all spaces removed.

The resulting string is:

  • “A00394BB”

Example 2: Remove Spaces from String Using tr

Once again, suppose that we have the following string in Bash:

  • ”    A00394BB “

Suppose that we would like to remove all spaces from this string.

We can use the following syntax to do so:

my_string="    A00394BB "
echo "$my_string" | tr -d ' '

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

Bash remove spaces from string using tr

This returns the string with all spaces removed.

The resulting string is:

  • “A00394BB”

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