Use Regex / Powershell to rename files
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 '_+',' ') }
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 }