我在CMD中使用Windows'Powershell从我的文件名中删除'Mon,tue,wed'等,它完美地运行
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日。
我怎么能这样做?
谢谢,迈克
您可以使用带有Rename-Item
的delay-bind script block将所需的转换组合成单个操作,其中-replace
operator允许您根据正则表达式(正则表达式)根据需要转换文件名。
Get-ChildItem -Recurse -Name | Rename-Item -NewName {
$_.Name -replace '\w+ (\d+) (\w+) (\d+)', '$3 $2 $1'
} -WhatIf
-WhatIf
预览重命名操作;删除它以执行实际重命名。
例如,名为Mon 13 July 2018 - Lorem ipsum
的输入文件将被重命名为
2018 July 13 - Lorem ipsum
。
注意:此示例文件名恰好没有文件扩展名,但上面和下面的解决方案同样适用于具有扩展名的文件名。
有关PowerShell的-replace
运算符的更多信息,请参阅this answer。
如果你想使用2018-07-13
这样的嵌入式格式来真正对你的文件名进行排序来表示13 July 2018
,那么需要通过-split
operator做更多的工作:
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
例如,名为Mon 13 July 2018 - Lorem ipsum
的输入文件将被重命名为
2018-07-13 - Lorem ipsum
。
有关PowerShell的qazxsw poi运算符的更多信息,请参阅qazxsw poi。
在帮助主题-split
中解释了分配给多个变量(this answer)
不是你的问题的答案,IMO mklement0的答案是最好的。
但是替代你的 丑陋 次优的样本代码。
基于RegEx的-replace运算符优于.replace()方法 当有替换时。
$null, $date, $rest = ...
返回当前语言环境的缩写日期名称,可以合并 在一个RegEx about_Assignment_Operators与代码
[Globalization.DatetimeFormatInfo]::CurrentInfo.AbbreviatedDayNames
空替换字符串不需要使用-replace运算符表示。
如果输出看起来没问题,请删除尾随-WhatIf
你可以链接每个月的替换,并以替换语句结束,以切换这样的数字
"(Sun|Mon|Tue|Wed|Thu|Fri|Sat) "
回归
$RE=[regex]"("+([Globalization.DatetimeFormatInfo]::CurrentInfo.AbbreviatedDayNames -join '|')+") "
Get-ChildItem -recurse -File | Rename-Item -NewName {$_.Name -replace $RE} -WhatIf
您可以使用以下代码转换日期
"13 July 2018 - Lorem ipsum" `
-replace 'July', '07' `
-replace 'Aug', '08' `
-replace "(\d+) (\d+) (\d+)", '$3 $2 $1'
这将输出
2018 07 13 - Lorem ipsum