1

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?

4
  • 2
    stackoverflow.com/q/40089631/2864740 Commented Jun 2, 2021 at 2:28
  • @user2864740 please see above, I've tried this. It doesn't work. Commented Jun 2, 2021 at 2:33
  • 1
    Try the response with 30 upvotes. Commented Jun 2, 2021 at 2:36
  • 1
    It is likely that the . is not being escaped for the regular expression context (in which case it represents a wildcard character). Commented Jun 2, 2021 at 2:41

3 Answers 3

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 \

Sign up to request clarification or add additional context in comments.

Comments

1

Other possibility without RegEx

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

Comments

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.