0

I got stuck at some point. Assuming following directory:

d:\example
             0 test1_123.txt
<DIR>          test1_123_abc0
             0 test2.txt
<DIR>          test2_123
<DIR>          test3_123_abc1
<DIR>          test4_test0_abc0

I want now to remove the postfix using regex '_abc*' of all directory names. I tried the following:

Get-ChildItem d:\example\ -Directory | foreach { rename-item $_ $_ -replace '_abc.' }

Does anybody know whats wrong here and can share the solution?

3
  • 1
    Try Get-ChildItem 'd:\example\' -Recurse -Filter *_abc* | Rename-Item -NewName { $_.name -replace '_abc\d*$', ''} Commented Jun 25, 2021 at 10:44
  • 1
    what do you think this >>> { rename-item $_ $_ -replace '_abc.' } <<< means? have you tested it? [grin] those two $_ items look oh-so-very-wrong ... Commented Jun 25, 2021 at 10:57
  • also, how do you want to handle the dupe dir names when truncating one makes it a dupe of another? Commented Jun 25, 2021 at 11:12

1 Answer 1

1

here's one solution to the problem ... [grin]

what it does ...

  • creates some files & dirs to test with
    when ready to do this for real, just remove the entire #region/#endregion block.
  • sets the target dir, dir filter, and regex remove pattern
    if you want to also remove _abc without any digits at the end, replace the + [one or more] with an * [zero or more].
  • grabs the list of matching dirs
  • iterates thru that list
  • renames the dir by stripping off the ending that matches the regex

please note that this DOES NOT handle name collisions. if you run this code twice you WILL see such when test5_abc666 gets renamed to test5 ... and a dir with that name already exists. [grin]

the code ...

#region >>> make some test files & dirs
@(
'test1_123.txt'
'test2.txt'
'test3_abc9.log'
) | ForEach-Object {
    $Null = New-Item -Path $env:TEMP -Name $_ -ItemType File -ErrorAction SilentlyContinue
    }
@(
'test1_123_abc0'
'test2_123'
'test3_123_abc1'
'test4_test0_abc0'
'test5_abc666'
) | ForEach-Object {
    $Null = New-Item -Path $env:TEMP -Name $_ -ItemType Directory -ErrorAction SilentlyContinue
    }
#endregion >>> make some test files & dirs

$TargetDir = $env:TEMP
$Filter = '*_abc*'
$Regex_ThingToRemove = '_abc\d+$'

$DirList = Get-ChildItem -LiteralPath $TargetDir -Directory -Filter $Filter
foreach ($DL_Item in $DirList)
    {
    Rename-Item -LiteralPath $DL_Item.FullName -NewName ($DL_Item.Name -replace $Regex_ThingToRemove)
    }
Sign up to request clarification or add additional context in comments.

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.