PowerShell: How to Trim Leading Spaces from String


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

Method 1: Trim Leading Spaces from One String

$my_string_trim = $my_string.TrimStart()

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

Method 2: Trim Leading Spaces from Each Line in File

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

This particular example trims the leading 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.

Related: How to Trim Trailing Spaces from String in PowerShell

Example 1: Trim Leading 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 leading spaces from the string:

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

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

PowerShell trim leading spaces from string

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

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

Example 2: Trim Leading 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 leading spaces.

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 82 total characters, including spaces.

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

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

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

PowerShell trim leading spaces from each line in file

Notice that the total character count of the file has dropped to 73, which indicates that all of the leading 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