PowerShell: How to Replace First Character in String


You can use the following syntax in PowerShell to replace the first character of each string in a file:

Get-Content old.txt | ForEach { $_ -replace "^#", "_" } | Set-Content new.txt

This particular example will replace the # character at the beginning of each string in the file named old.txt and save the results to a new file named new.txt.

Here is what the various commands do:

  • Get-Content: Returns all lines from the text file
  • ForEach: Specifies an action to perform on each line of the file
  • $_: Returns the existing text from current line
  • -replace “^#”, “_”: Replaces the starting ( ^ ) character of # with _
  • Set-Content: Saves the updated content to a specific text file

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

Example: How to Replace First Character in String Using PowerShell

Suppose we have a file named team_list.txt in our current directory that contains the names of various basketball teams.

We can use the Get-Content cmdlet to view the contents of this file:

PowerShell replace first character in string

Suppose that we would like to replace the # character at the start of each line with an underscore instead.

We can use the following syntax to do so:

Get-Content team_list.txt | ForEach { $_ -replace "^#", "_" } | Set-Content team_list2.txt

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

PowerShell replace first character in string

Notice that when we use the Get-Content cmdlet to view the contents of the new team_list2.txt file we can see that the first character in each line has been replaced with an underscore.

Note: You can find the complete documentation for the Foreach statement in PowerShell here.

Related Tutorials

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

PowerShell: How to Replace Comma with Newline
PowerShell: How to Replace Specific Text in Multiple Files
PowerShell: How to Replace Only First Occurrence of Word in String

Leave a Reply