How to Remove Leading Zeros in PowerShell (With Examples)


Often you may want to remove leading zeros from variables in PowerShell.

You can use the following methods to do so:

Method 1: Remove Leading Zeros from Variable

$new_var = $my_var -replace '^0+', ''

This particular example removes the leading zeros from the variable named $my_var and stores the results in a new variable named $new_var.

Note that ^ represents the start of a string in Regex and the + after the zero specifies that we’d like to replace all leading zeros with nothing.

Method 2: Remove Leading Zeros from Each Line in File

(gc original_file.txt)| % {$_ -replace '^0+', ''} | sc new_file.txt

This particular example removes the leading zeros from each line in the file named original_file.txt and stores the results in a new file named new_file.txt.

Note the following:

  • gc is an alias for Get-Content
  • % is an alias for ForEach-Object
  • sc is an alias for Set-Content

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

Example 1: Remove Leading Zeros from Variable in PowerShell

Suppose that we have a variable named $my_var in PowerShell that contains the following employee ID:

  • 0000AAHB4

We can use the following syntax to create a new variable named $new_var that removes all of the leading zeros from this employee ID:

$my_var = '0000A0AHB4'
$new_var = $my_var -replace '^0+', ''

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

PowerShell remove leading zeros from variable

Notice that all leading zeros have been removed from the variable named $new_var.

Also notice that any zeros that are not leading zeros are kept in the string.

Example 2: Remove Leading Zeros from Each Line in File in PowerShell

Suppose that we have a file named employees.txt that contains the employee ID’s of various employees at some company.

We can use the Get-Content cmdlet to view each of the lines in this file:

Notice that all of the employee ID values have leading zeros.

We can use the following syntax to remove the leading zeros from each line in the file and save the results to a new file named employees_new.txt:

(gc employees.txt)| % {$_ -replace '^0+', ''} | sc employees_new.txt

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

PowerShell remove leading zeros from each line in file

When we use the Get-Content cmdlet to view the contents of the new employees_new.txt file we can see that the leading zeros have been removed from each line in the file.

Related Tutorials

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

PowerShell: How to Trim Leading Spaces from String
PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Extract Only Numbers from String

Leave a Reply