开发者

Renaming files with an index in the bracket

I'd like to write a short powershell script for renaming files like:

abc(1), abc(2), .., abc(10), ..,  abc(123), .. 
开发者_高级运维

to

abc(001), abc(002), .., abc(010), .., abc(123), ..

Any idea? :)


Try this:

Get-ChildItem abc* | Where {$_ -match 'abc\((\d+)\)'} | 
 Foreach {$num = [int]$matches[1]; Rename-Item $_ ("abc({0:000})" -f $num) -wh }

The Where stage of the pipeline is doing to two things. First, only filenames that match the specified pattern are passed along. Second, it uses a capture group to grab the numeric part of the name which is sitting in $matches[1].

The Foreach stage applies script to each item, represented by $_, passed into it. The first thing it does is to get the "numeric" part of the old filename. Then it uses Rename-Item (PowerShell's rename command) to rename from the old name represented by $_ to the new name that is computed using a formatting string "abc({0:000})" -f $num. In this case, the formatting directive goes in {} where 0 represents the position of the value specified after -f. The :000 is a formatting directive displays number with up to three leading zeros. Finally the -wh is short for -WhatIf which directs potentially destructive operations like Rename-Item to show what it would do without actually doing anything. Once you are satisfied the command is working correctly, remove the -wh and run it again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜