Complex file rename
I have some 100 files in a folder. I want to rename those files. The format of files is like
AB1234.gif
B3245.gif
AB2541.gif
AB11422.jpg
and so on..
Output files shld be
AB-0111-1.gif
B-0111-2.gif
AB-0111-3.gi开发者_StackOverflowf
AB-0111-4.jpg
Logic will be
for(int n=0;n<files.count;n++){
if(file is starting with AB)
fileName = AB + "-0111" + n;
if(file is starting with B)
fileName = B + "-0111" + n;
}
Is this thing possible with powershell script?
With the filename format that you describe, you can use the powershell -replace
operator to replace the middle digits with the expression that you want. The only tricky part is that you have to maintain a counter as you loop through the items. It would look like this:
dir | foreach -begin{$cnt = 1} -process { mv $_ ($_.Name -replace '\d+',"-0111-$cnt"); $cnt += 1}
You can use [System.IO.Path]::GetExtension to get the extension of the file like this:
$ext = [System.IO.Path]::GetExtension('AB1234.gif')
and you can get the first alpha characters of the file name using the $matches
variable like this:
if ('AB1234.gif' -match '^\D*') { $first = $matches[0]; }
and you can build your new file name like this:
$first + '-0111-' + '1' + $ext
You can replace the '1' above with a variable that you can increment by checking the exists property like this:
$i = 1;
while (test-path ($first + '-0111-' + $i + $ext)) {$i++}
when this loop completes, you will have the file name you need with $first + '-0111-' + $i + $ext
and you can use this to rename the file with Rename-File
:
Rename-File 'AB1234.gif' ($first + '-0111-' + $i + $ext)
now, wrap all that up in a loop and you should have it:
dir | ForEach-Object { ... }
for testing, add the -whatif
parameter to the end of the Rename-File
command and PS will tell you what it would do instead of actually performing the action.
thanks, mark
精彩评论