Dean
Dean

Reputation: 1153

Use Regex / Powershell to rename files

How does one rename the following files (New => Old):

filename__Accelerated_C____Practical_Programming_by_Example.chm -> C Practical Programming by Example.chm

filename__Python_Essential_Reference__2nd_Edition_.pdf -> Python Essential Reference 2nd Edition.pdf

filename__Text_Processing_in_Python.chm -> Text Processing in Python.chm

Upvotes: 36

Views: 51672

Answers (3)

zdan
zdan

Reputation: 29470

This should work:

ls | %{ ren $_ $(($_.name -replace '^filename_+','') -replace '_+',' ') }

Expanding the aliases and naming all argument, for a more verbose but arguably more understandable version, the following is equivalent

Get-ChildItem -Path . | ForEach-Object { Rename-Item -Path $_ -NewName $(($_.Name -replace '^filename_+','') -replace '_+',' ') }

Upvotes: 35

stej
stej

Reputation: 29479

Try this one:

Get-ChildItem directory `
        | Rename-Item -NewName { $_.Name -replace '^filename_+','' -replace '_+',' ' }

Note that I just pipe the objects to Rename-Item, it is not really needed to do it via Foreach-Object (alias is %).

Update

I haven't anything documented about the 'magic' with scriptblocks. If I remember correctly, it can be used if the property is ValueFromPipelineByPropertyName=$true:

function x{
    param(
        [Parameter(ValueFromPipeline=$true)]$o,
        [Parameter(ValueFromPipelineByPropertyName=$true)][string]$prefix)
    process {
        write-host $prefix $o
    }
}
gci d:\ | select -fir 10 | x -prefix { $_.LastWriteTime }

Upvotes: 55

ridgerunner
ridgerunner

Reputation: 34435

Try this out:

$filename = $filename -creplace '_+\.', '.'
$filename = $filename -creplace '_+', ' '

Upvotes: 1

Related Questions