Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 526
Dean Avatar asked Apr 07 '11 00:04

Dean


People also ask

How do I rename multiple files in PowerShell?

Open File Explorer, go to a file folder, select View > Details, select all files, select Home > Rename, enter a file name, and press Enter. In Windows PowerShell, go to a file folder, enter dir | rename-item -NewName {$_.name -replace “My”,”Our”} and press Enter.

Can you use regex in PowerShell?

Powershell: The many ways to use regex The regex language is a powerful shorthand for describing patterns. Powershell makes use of regular expressions in several ways. Sometimes it is easy to forget that these commands are using regex becuase it is so tightly integrated.

How do I rename an item in PowerShell?

To rename and move an item, use Move-Item . You can't use wildcard characters in the value of the NewName parameter. To specify a name for multiple files, use the Replace operator in a regular expression.

How do I rename a folder in PowerShell?

Cmdlet. Rename-Item cmdlet is used to rename a folder by passing the path of the folder to be renamed and target name.


2 Answers

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 } 
like image 76
stej Avatar answered Oct 02 '22 01:10

stej


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 '_+',' ') } 
like image 42
zdan Avatar answered Oct 02 '22 00:10

zdan