Home > front end >  Replacing only part of the file name in Powershell
Replacing only part of the file name in Powershell

Time:10-14

I got a problem with powershell and some pdfs names

So there is a bunch of them:

2021_01_21_Aneks_nr2.pdf
2021_11_31_Aneks_nr3.pdf
2021_05_04_Aneks_nr4.pdf

I need to replace "_" with "-" but only near date. Output should look like this:

2021-05-04_Aneks_nr4.pdf

I'm new to programming and couldn't find solution in internet. I was using this code :

Get-Childitem | foreach { rename item $_ $_.Name.Replace("_","-") }

But it works on all "_" so I cant use it in this scenario.

Thanks for help! :)

CodePudding user response:

Using the -replace operator instead of the dot net method you can use regex. And there you can specify to replace only underlines between digits:

Get-ChildItem |
ForEach-Object {
    Rename-Item -Path $_.FullName -NewName $($_.Name -replace '(?<=\d)_(?=\d)', '-')
}

CodePudding user response:

Here you go

#Loop through files
get-childitem [path] | ForEach-Object {
    #match pattern
    $null = $_.name -match '\d{4}_\d{2}_\d{2}'
    #get matching pattern
    $pattern = $matches[0]
    #replace _ with -
    $replace = $pattern -replace '_','-'
    #build new name
    $newName = $_.name -replace $pattern,$replace
    #rename file
    rename-item -Path $_.fullname -NewName $newName
}

It matches the current name of the file for the pattern '\d{4}_\d{2}_\d{2}', gets the matching string, replaces _ with - and finally build the new name by replacing the matching string with the updated version.

  • Related