Rename files by reformatting the date string embedded in their names
我正在CMD中使用Windows的Powershell从我的文件名中删除"星期一,星期二,星期三"等,效果很好
1 2 3 4 5 6 | Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace("Mon","") } Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace("Tue","") } Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace("Wed","") } Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace("Thur","") } Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace("Fri","") } Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace("Sat","") } |
现在我的文件名看起来像这样:
2018年7月13日-Lorem ipsum
我想用月份切换日期,所以它将是:
2018年7月13日,所以我可以按月对其进行排序。甚至是2018年7月13日。
我该怎么做?
谢谢,
迈克
您可以使用
1 2 3 | Get-ChildItem -Recurse -Name | Rename-Item -NewName { $_.Name -replace '\\w+ (\\d+) (\\w+) (\\d+)', '$3 $2 $1' } -WhatIf |
例如,名为
注意:此示例文件名碰巧没有文件扩展名,但是上面和下面的解决方案都可以使用具有扩展名的文件名。
有关PowerShell的
如果要使用诸如
1 2 3 4 5 6 7 8 | Get-ChildItem -Recurse -Name | Rename-Item -NewName { # Split the name into the date part (ignoring the weekday) and the # rest of the file name. $null, $date, $rest = $_.Name -split '\\w+ (\\d+ \\w+ \\d+)' # Convert the date string to [datetime] instance, reformat it, and # append the rest. ([datetime] $date).ToString('yyyy-MM-dd') + $rest } -WhatIf |
例如,名为
有关PowerShell的
帮助主题about_Assignment_Operators
中介绍了分配给多个变量(
不是您的问题的答案,IMO mklement0的答案最有效。
但是代替了 ugly s>次优示例代码。
基于RegEx的-replace运算符优于.replace()方法
当有替换替换时。
1 | [Globalization.DatetimeFormatInfo]::CurrentInfo.AbbreviatedDayNames |
返回当前语言环境的缩写天名称,可以将其组合
在一个RegEx
1 2 3 | $RE=[regex]"("+([Globalization.DatetimeFormatInfo]::CurrentInfo.AbbreviatedDayNames -join '|')+")" Get-ChildItem -recurse -File | Rename-Item -NewName {$_.Name -replace $RE} -WhatIf |
不需要使用-replace运算符来表示空的替换字符串。
如果输出看起来不错,请删除结尾的-WhatIf
您可以使用以下代码转换日期
1 2 3 | $string = '13 July 2018 - Lorem ipsum' $dateObject = [datetime]$string.Split('-')[0] Write-Output"$($dateObject.ToString('yyyy MMMM dd')) - $($array[1])" |
这将输出
1 | 2018 July 13 - Lorem ipsum |
您可以将每个月的替换链接起来,并以replace语句结尾来切换这样的数字
1 2 3 4 | "13 July 2018 - Lorem ipsum" ` -replace 'July', '07' ` -replace 'Aug', '08' ` -replace"(\\d+) (\\d+) (\\d+)", '$3 $2 $1' |
夹心返回
1 | 2018 07 13 - Lorem ipsum |