Quizzed
Quizzed

Reputation: 173

How to replace a character at the end of a string/file?

I'm trying to remove a rogue comma at the end of my file when formatting with PowerShell. The file in question contains the user's city, region, and country.

Example:

San Diego, California, US, 

But I want it to be:

San Diego, California, US

How can I remove this last ', ' at the end using -replace? My code doesn't work below:

(Get-Content file.txt) | ForEach-Object {
    $_ -replace ', ', ''
} | Set-Content file.txt

I just need a way of detecting that last ', ' that appears in my file without removing every comma that exists in the file.

Upvotes: 3

Views: 3298

Answers (3)

P-L
P-L

Reputation: 533

You can also simply use the LastIndexOf function of the String class combined with a Substring.

$test = "San Diego, California, US, "
Write-Host $test.Substring(0, $test.LastIndexOf(','))

output: San Diego, California, US

Pretty self explaining --> You select from the start of the string until the last index of your specified char or string.

This is, assuming you always have your rogue comma at the end of the string, otherwise it will trim the text after a "good" comma.

Upvotes: 2

Lee_Dailey
Lee_Dailey

Reputation: 7479

while the regex solution is likely faster than string methods, you can use string methods to do the job. [grin]

  • use .Trim() to remove any leading or trailing whitespace
  • use .TrimEnd(',') to remove any trailing comma chars

like this ...

'San Diego, California, US, '.Trim().TrimEnd(',')

output = San Diego, California, US

Upvotes: 2

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

You need to anchor your expression at the end of the string. In regular expressions that is done with a $ character. Add a \s* if you want to ignore trailing whitespace after that last comma:

$_ -replace ',\s*$'

Upvotes: 5

Related Questions