【问题标题】:delete characters to the right of the second space in filename删除文件名中第二个空格右侧的字符
【发布时间】:2012-10-23 13:05:25
【问题描述】:

我会不断地将文件从外部服务器复制到本地服务器。文件名的格式如下:

Example 1     Invoice MM500780 10 26 2012 3 52 15 PM.PDF
Example 2     Invoice PS100679-02 10 30 2012 9 31 35 AM.PDF
Example 3     Return RTN001116 10 26 2012 8 59 56 AM.PDF

我想通过修剪第二个空格(代表日期和时间)之后的任何字符来重命名所有文件。文件名应为:

Example 1     Invoice MM500780.PDF
Example 2     Invoice PS100679-02.PDF
Example 3     Return RTN001116.PDF

无论如何我可以创建一个 powershell 文件并通过任务管理器运行它吗?

感谢您的帮助。

【问题讨论】:

  • 为什么要使用 PowerShell 来完成这项任务?您是只需要重命名其中的一组文件,还是计划将来重命名多个文件?
  • @Christian 我尝试使用 bat 文件 == '@echo off for /f "tokens=*" %%a in ('dir /b /ad *.pdf') do (for / f "tokens=1" %%b in ("%%a") do ren "%%a" "%%b.pdf" ) )' 但是,这只会将文件重命名为第一个单词
  • @Mikhail,是的,我会每天重命名文件。

标签: powershell


【解决方案1】:

尝试:

dir c:\mydir -filter *.pdf | 
% {rename-item -path $_.fullname -newname ( ($_.name.split('')[0..1] -join ' ' ) + $_.Extension )}

【讨论】:

    【解决方案2】:

    根据 Christian 的帖子,这是他使用 Regex 模式匹配的代码。

    [regex]$regex = "\A\S*[\s]\S*"
    
    dir c:\mydir -filter *.pdf | % {rename-item -path $_.fullname -newname ($regex.matches($_.BaseName)[0].value + $_.Extension )}
    

    更改正则表达式以更改命名模式。使用正确的模式,您应该能够提取原始名称的任何部分以用作新名称。 模式是\A开头的字符串,\S非空白字符(*任意数字),\s空白,\S非空白字符(*任意数字)

    【讨论】:

      【解决方案3】:

      我相信您正在寻找的正是这些方面的东西?

      Split string with PowerShell and do something with each token

      基本上你会在空格处拆分文件名,然后将文件重命名为第一个和第二个标记中的任何内容。

      【讨论】:

      • 感谢 ParrotMac 的回复,我试过了:@echo off for /f "tokens=*" %%a in ('dir /b /ad *.pdf') do (for /f" tokens=1" %%b in ("%%a") do ren "%%a" "%%b.pdf" ) ) 但是得到 invoice.pdf return.pdf 我不知道如何组合和输出两个令牌
      • @ ParrotMac 感谢您的回复我试过了:'@echo off for /f "tokens=*" %%a in ('dir /b /ad *.pdf') do (for /f "tokens=1" %%b in ("%%a") do ren "%%a" "%%b.pdf" ) )' 但是得到 invoice.pdfreturn .pdf 作为文件名我不知道如何组合和输出两个标记
      【解决方案4】:

      这个 powershell one liner 应该可以满足您的需求。

      Get-ChildItem | %{$splitName = $_.Name.Split(" ", 3); if($splitName.Length -gt 2) {$finalName = [string]::Join("",[string]::Join(" ",$splitName[0],$splitName[1]),$_.Extension); Rename-Item -Path $_.FullName -NewName $finalName}}
      

      【讨论】:

      • ...感谢您的回复...我是新手...我尝试了您的代码并收到错误 Rename-Item : Cannot bind argument to parameter 'NewName' 因为它为空.
      猜你喜欢
      • 2016-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-01
      • 2019-02-28
      • 2020-11-17
      • 2021-11-29
      • 2016-04-15
      相关资源
      最近更新 更多