0

I've got a file with a unique substring in the file name. Therefore I'm matching it with a regex. For example, lets say that the file name is someFile.asdf1234.txt.

$fileNameRegex = [regex] 'someFile\.(.*).txt'
$fileName = Get-ChildItem C:\test | Where-Object {$_.Name -Match $fileNameRegex}
#         $fileName = 'someFile.asdf1234.txt'
#         so far this works.

What I'm having a hard time doing is use this info to rename the file

$arbitraryString = "random9753"
# the final file name needs to be "someFile.random9753.txt"

How do I reuse the same regex to rename the substring portion of the file name with the new $arbitrartyString?

note: I don't mind changing the regex to meet the needs (possibly using groups), but I need to only have a single regex.

2
  • I'm not following where you're having a problem...with the regex or the file rename? Commented Mar 28, 2013 at 18:35
  • I tried to clarify in an edit. Commented Mar 28, 2013 at 18:40

2 Answers 2

2

Here's one way:

$fileNameRegex = [regex] '(someFile\.).*(\.txt)'
$fileName = 'someFile.asdf1234.txt'
$arbitraryString = "random9753"

$fileName -match $fileNameRegex > $nul
"$($matches[1])$arbitraryString$($matches[2])"

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

Comments

1

One solution is to pull apart the file name into substrings and then concatenate them together.

$filename = "someFile.asdf1234.txt"
$arbitraryString = "random9753"


$newfilename = $filename.substring(0,$filename.IndexOf("."))
$newfilename += '.' + $arbitraryString + '.'
$newfilename += $filename.Substring($filename.Length -3)

Write-Host $newfilename

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.