Powershell renaming a specific Character

只愿长相守 提交于 2020-01-05 04:17:09

问题


I've been batch renaming .las files in powershell with a simple script:

cd "C:\Users\User\desktop\Folder"
Dir | Rename-Item -NewName {$_.name-replace "-", "" }
Dir | Rename-Item -NewName {$_.name-replace "_", "" }
Dir | Rename-Item -NewName {$_.BaseName+ "0.las"}

This has been working great, but I need to modify it to account for a different naming convention.

The files start out in this format: 123_45-67-890-12W_0 and get converted to 123456789012W00.las

Occasionally the number after the W will be non zero, and I need to carry that on as the last digit, eg. 123_45-67-890-12W_2 needs to go to 123456789012W02

I'm not sure how to use if statements and to select a specific digit in powershell format, which is how I would approach this problem. Does anyone have some ideas on how to go about this?

Thanks


回答1:


You can use the substring method to get all but the last character in the basename, then concatenate the zero, then use substring again to get the basename's last character, then finish off with the .las extension:

Dir | Rename-Item -NewName {($_.BaseName).substring(0,$_.BaseName.length - 1) + "0" + ($_.BaseName).substring($_.BaseName.length -1,1) + ".las"}
#                           ^^^^This gets everything but the last charcter^^^         ^^^^^^^^^^This gets the last character^^^^^^^^^^



回答2:


You can use a regular expression to achieve this:

Get-ChildItem "C:\Users\User\desktop\Folder" | ForEach-Object {

    #capture everything we need with regex
    $newName = $_.Name -replace "(\d{3})_(\d{2})-(\d{2})-(\d{3})-(\d{2})(\w)_(\d)",'$1$2$3$4$5$6$7'

    #insert 0 before last digit and append file extension
    $newName = $newName.Insert(($newName.Length - 1), "0") + ".las"

    #rename file
    Rename-Item $_.FullName -NewName $newName
}


来源:https://stackoverflow.com/questions/38019236/powershell-renaming-a-specific-character

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