deeej
deeej

Reputation: 387

How do I replace the first occurrence of a period in a powershell string?

I have the following PowerShell:

$img="john.smith.jpg"
$img.Replace(".", "")

I'm trying to replace the first occurrence of a a period in the string.

At the moment it replaces all periods and returns: "johnsmithjpg"

The output I'm looking for is: "johnsmith.jpg".

I also tried the following but it doesn't work:

$img="john.smith.jpg"
[regex]$pattern = "."
$img.replace($img, "", 1)

What do I need to do to get it to only replace the first period?

Upvotes: 1

Views: 1732

Answers (3)

Theo
Theo

Reputation: 61068

Seems to me that $img contains a filename including the extension. By blindly replacing the first dot, you might end up with unusable (file)names.
For instance, if you have $img = 'johnsmith.jpg' (so the first and only dot there is part of the extension), you may end up with johnsmithjpg..

If $img is obtained via the Name property of a FileInfo object (like Get-Item or Get-ChildItem produces),

change to:

$theFileInfoObject = Get-Item -Path 'Path\To\johnsmith.jpg'  # with or without dot in the BaseName
$img = '{0}{1}' -f (($theFileInfoObject.BaseName -split '\.', 2) -join ''), $theFileInfoObject.Extension
# --> 'johnsmith.jpg'

Or use .Net:

$img = "johnsmith.jpg"  # with or without dot in the BaseName
$img = '{0}{1}' -f (([IO.Path]::GetFileNameWithoutExtension($img) -split '\.', 2) -join ''), [IO.Path]::GetExtension($img)
# --> 'johnsmith.jpg'

Upvotes: 1

Civette
Civette

Reputation: 538

Other possibility without RegEx

$img="john.smith.jpg"
$img.Remove($img.IndexOf("."),1)

Upvotes: 1

randomcoder
randomcoder

Reputation: 646

From Replacing only the first occurrence of a word in a string:

$img = "john.smith.jpg"
[regex]$pattern = "\."
$img = $pattern.replace($img, "", 1)

Output:

enter image description here

Note for the pattern, . is treated as a wildcard character in regex, so you need to escape it with \

Upvotes: 2

Related Questions