I stumbled across this post by Rob Newcater on RootPrompt.org which points to this post on BasicallyTech.com. It shows the various ways that you can rename or manipulate filenames in groups using the bash shell and a smattering of standard UNIX utilities.
The sample given was renaming a directory full of *.mp3 files such that all the spaces were replaced with underscores – here is the script in BASH:
for FILE in *.mp3 ; do NEWFILE=`echo $FILE | sed ’s/ /_/g’` ; echo “$FILE will be renamed as $NEWFILE” ; done
That is pretty cool, although it is much more concise in PowerShell:
get-childitem *.mp3 | foreach { rename-item $_ $_.Name.Replace(” “, “_”) }
And by concise, I don’t mean shorter. One of the advantages of PowerShell over traditional text-piping shells is that you are dealing with objects which provide a lot more data to the next part of the processing pipeline. If you are into punctuation you could express it as:
gci *.mp3 | % { rename-item $_ $_.Name.Replace(” “, “_”) }
But to be honest, I prefer it the first way.
December 1, 2006 at 7:47 pm
a bit late but TIMTOWTDI
dir *.mp3 | ren -n {$_.name -replace ” “,”_”} -whatif
and -WhatIF beats the Echo line added in the bash example I think
PoSH>dir *.mp3 | ren -n {$_.name -replace ” “,”_”} -whatif
What if: Performing operation “Rename File” on Target “Item: C:\PowerShell\foo bar.mp3 Destination: C:\PowerShell\foo_bar.mp3″.
Greetings /\/\o\/\/
March 26, 2007 at 9:12 pm
Thanks! I looked in the docs and couldn’t find such an example anywhere. You provided exactly what a Powershell newbie needed.