【问题标题】:Remove certain characters from all folder names in a folder从文件夹中的所有文件夹名称中删除某些字符
【发布时间】:2020-12-11 22:26:08
【问题描述】:

我有一个文件夹,其中包含大量子文件夹,其文件夹名称的开头带有随机数。它们采用这种格式:

1254170-folder1
1212340-folder2
3245417-folder3

我可以将它们全部重命名为什么

folder1
folder2
folder3

我尝试了类似的方法,因为我看到了类似的文件名。

for f in *\1*;do( mv "$f" "${f//1/ }");done

但它不起作用。 powershell 返回了

At line:1 char:4
+ for f in *\1*;do( mv "$f" "${f//1/ }");done
+    ~
Missing opening '(' after keyword 'for'.
At line:1 char:17
+ for f in *\1*;do( mv "$f" "${f//1/ }");done
+                 ~
Missing statement body in do loop.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingOpenParenthesisAfterKeyword

不知道我该怎么办。我正在使用 Windows 10 2004。 感谢您的帮助。

【问题讨论】:

    标签: powershell directory windows-10 subdirectory batch-rename


    【解决方案1】:

    这应该可行:

    Get-ChildItem -path . -directory -recurse | Where {$_.Name -match '^\d+-'} | Rename-Item -NewName {$_.Name -replace '^\d+-',''}
    
    • 第一个命令枚举当前目录 (.) 中的文件夹和所有子文件夹。
    • 第二个命令过滤以数字开头后跟破折号 (^\d+- regex) 的文件夹
    • 第三个命令通过删除 ^\d+- 前缀重命名文件夹

    【讨论】:

      【解决方案2】:

      我完成了@Renat 代码:

      如果您想排除格式为“-”后不带字符的目录(例如 1254170-)

      如果你希望你的脚本在新名称的目录已经存在的情况下继续执行

      Get-ChildItem "c:\temp\" -dir | where name -match "^\d+-.+$" | Rename-Item -NewName {$_.Name.Split('-')[1]} -ErrorAction SilentlyContinue
      

      【讨论】:

      • 如果文件夹名称包含两个或多个破折号,$_.Name.Split('-')[1] 将无法按预期工作..
      猜你喜欢
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      • 2021-07-24
      相关资源
      最近更新 更多