如何从文本文件中修剪日期。例如,我有多个文件,如:
- test_20091011.txt
- try_20091011.txt
- 文件夹_20091011.txt
我想换成:
- test.txt
- try.txt
- fold.txt
谢谢。
假设文本文件名格式不变,则此代码应该可以工作,因为在中,它总是需要删除的最后9个字符。此代码假定txt文件位于文件夹C:\folder 中
$filelist = (get-childitem c:folder | Where-Object {$_.mode -match "a"} | foreach-object {$_.name})
foreach ($file in $filelist)
{
$len = $file.length
$newname = $file.substring(0,$len -13)
$newname = $newname + '.txt'
Rename-Item C:folder$file $newname
clear-variable newname, len
}
根据命名模式的类型,答案会发生微妙的变化,但在您的情况下,您可以使用这样的脚本来实现这一点:
Get-ChildItem |
Where-Object {
<#
Multiple Assignment in PowerShell.
$beforeUnderbar will have your name,
$AfterUnderBar will have the data, and
$extension will have the extension.
All from one little -split
If you start throwing random other files in there, it will barf.
#>
$beforeUnderbar, $afterUnderBar, $extension = ($_.Name -split "[_.]")
if ($afterUnderBar -and $afterUnderBar.Length -eq 8 -and $afterUnderBar -as [int]) {
"$beforeUnderBar.$extension"
}
}
该脚本应该为您提供与命名约定相匹配的文件所需的内容。