Powershell replacing periods

岁酱吖の 提交于 2019-11-30 00:03:21

问题


Can anyone tell me if they think there is something wrong with this Powershell script.

Dir | 
where {$_.extension -eq ".txt"} | 
Rename-Item –NewName { $_.name –replace “.“,”-” }

For each text file in the current directory, I'm trying to replace all periods in the file names with hyphens. Thanks ahead of time.


回答1:


As the others have said, -replace uses regex (and "." is a special character in regex). However, their solutions are forgetting about the fileextension and they are acutally removing it. ex. "test.txt" becomes "test-txt" (no extension). A better solution would be:

dir -Filter *.txt | Rename-Item -NewName { $_.BaseName.replace(".","-") + $_.Extension }

This also uses -Filter to pick out only files ending with ".txt" which is faster then comparing with where.




回答2:


-replace operates on regex, you need to escape '.':

rename-item -NewName { $_.Name -replace '\.', '-' }

Otherwise you will end up with '----' name...




回答3:


The name property of a file object in powershell is of type string.
That means, you could also use the static string method replace like follows and don't care about regex' reserved characters:

dir | ? { $_.extension -eq ".txt" } | rename-item -newname { $_.name.replace(".","-") }


来源:https://stackoverflow.com/questions/14541980/powershell-replacing-periods

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