0

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?

deeej
  • 357
  • 1
  • 6
  • 22

3 Answers3

2

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 \

randomcoder
  • 626
  • 7
  • 20
1

Other possibility without RegEx

$img="john.smith.jpg"
$img.Remove($img.IndexOf("."),1)
Civette
  • 386
  • 2
  • 10
1

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'
Theo
  • 57,719
  • 8
  • 24
  • 41