PowerShell Regex Bulk Replace Filenames [duplicate]

ε祈祈猫儿з 提交于 2019-12-24 20:51:22

问题


I am trying to replace filenames in a given folder, but using regular expressions as a filter and in the new filenames, in PowerShell.

For example, a file name "CEX-13" should be renamed to "C-0013"; "CEX-14" should change to "C-0014", etc.

I have this, but I get an error that I cannot create a file that already exists.

My current code is:

foreach ($file in get-childitem | where-object {$_.name -match "^CEX-(\d\d)"})
{
    rename-item $file -newname ($file.name -replace "^CEX-(\d\d)", "C-00$1")
}

Any help will be greatly appreciated.


回答1:


You need the dollar in the replacement to get past the PowerShell variable expansion in strings, and stay as a dollar sign as it gets to the regex engine.

Currently "C-00$1" becomes "C-00" and all the files will get the same name.

You need to escape it with a backtick

"C-00`$1"

or use single quotes 'C-00$1'



来源:https://stackoverflow.com/questions/49394169/powershell-regex-bulk-replace-filenames

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!