PowerShell: How to Trim Trailing Spaces from String


You can use the following methods in PowerShell to trim trailing spaces from a string:

Method 1: Trim Trailing Spaces from One String

$my_string_trim = $my_string.TrimEnd()

This particular example trims the trailing spaces from the string variable named $my_string and stores the results in a new variable named $my_string_trim.

Method 2: Trim Trailing Spaces from Each Line in File

(gc $my_file)| % {$_.TrimEnd()} | sc $my_file

This particular example trims the trailing spaces from each line in the file specified at the path in the $my_file variable.

The following examples show how to use each method in practice.

Example 1: Trim Trailing Spaces from One String in PowerShell

Suppose that we have a string variable named $my_string in PowerShell that contains the following string:

  • ”  Dallas     “

This particular string has two leading spaces and five trailing spaces.

We can use the following syntax to trim only the trailing spaces from the string:

$my_string = "  Dallas     "
$my_string_trim = $my_string.TrimEnd()

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

PowerShell trim trailing spaces from string

Notice that the length of the original string was 13 characters while the length of the trimmed string is 8 characters.

The five trailing spaces have been trimmed from the string while the two leading spaces have been kept.

Example 2: Trim Trailing Spaces from Each Line in File

Suppose that we have a file named city_names.txt that contains the names of various U.S. cities with leading and trailing blanks.

We can use the gc command (as an alias for Get-Content) to view each of the lines in this file:

$my_file = "c:\users\bobbi\city_names.txt"
gc $my_file

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

Several of the lines have trailing spaces although we can’t see them in the output.

To view the total number of characters in the file (including spaces) we can use the following syntax:

(gc $my_file | Measure-Object -Character).Characters

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

We can see that the file currently has 84 total characters, including spaces.

To remove the trailing spaces from each line in the file, we can use the following syntax:

(gc $my_file)| % {$_.TrimEnd()} | sc $my_file

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

PowerShell trim trailing spaces from each line in file

Notice that all of the leading spaces are still visible in each line but the total character count of the file has dropped to 67, which indicates that all of the trailing spaces have been trimmed from each line.

Related Tutorials

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

PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Extract Only Numbers from String
PowerShell: How to Replace Special Characters in String

Leave a Reply