powershell - How would I change multiple filenames in Powershell?
问题描述
I am trying to remove parts of a name "- xx_xx" from the end of multiple files. I'm using this and it works well.
dir | Rename-Item -NewName { $_.Name -replace " - xx_xx","" }
However, there are other parts like:
" - yy_yy" " - zz_zz"
What can I do to remove all of these at once instead of running it again and again changing the part of the name I want removed?
解决方案
最简单的方法
如果需要,您可以继续串-replace
语句直到奶牛回家。
$myLongFileName = "Something xx_xx yy_yy zz_zz" -replace "xx_xx","" -replace "yy_yy"
更简洁的语法
如果每个文件都有这些,你也可以制作一个你想要替换的数组,就像这样,只是用逗号分隔它们。
$stuffWeDontWantInOurFile =@("xx_xx", "yy_yy", "zz_zz")
$myLongFileName -replace $stuffWeDontWantInOurFile, ""
还有一种方式
如果您的文件元素由空格或破折号或可预测的东西分隔,您可以在其上拆分文件名。
$myLongFileName = "Something xx_xx yy_yy zz_zz"
PS> $myLongFileName.Split()
Something
xx_xx
yy_yy
zz_zz
PS> $myLongFileName.Split()[0] #select just the first piece
Something
对于空格,您使用Spit()
其中没有重载的方法。
如果它是破折号或其他字符,你会像这样提供它Split("-")
。在这些技术之间,你应该能够做你想做的事情。
推荐阅读
- c# - SQLite; 是否有参数每次重写一条记录
- angular - CloneDeep 导致滚动条出现问题
- swift - 你能将 Swift 泛型约束限制为一组已知类型吗?
- r - 如何使用 R 中的循环函数填充表格?
- ios - 移除基于平台的 pod 依赖
- r - 将 R Leflet 地图上传到 RPubs 时出现一致的错误
- laravel - “此路由不支持 GET 方法。支持的方法:POST”消息在我的 laravel API 中
- sml - 编写一个 SML 函数,该函数采用文件名并返回不带空格的 char 列表
- javascript - 如何在我的 Jquery 代码中进行调整查看问题描述
- r - Rmarkdown 转换的严重问题