如何解决使用Windows PowerShell将.csv文件名中的日期解析为多个.csv文件的新列
我有一系列数据文件,其中包含给定日期的数据,其标题为:“ 2019年8月27日Measurement Log.csv”
这些文件中的时间戳数据仅包含时间,而不包含日期。对于每个文件(有几百个),我想从标题中捕获日期,并用适当的值填充第一列。输出的.csv文件将在每个单元格中填充一个“日期”列,并在其中填充“ 8/27/2019”(但仅包含与数据点一样多的行)。
在此先感谢您提供的任何帮助或建议!
解决方法
不确定这是否正是您所需要的,但希望可以为您指明正确的方向。它所要做的就是遍历文件,从名称中获取日期,然后获取CSV数据,并将新成员添加到输出中。如果希望将选择对象作为第一列的日期,则可能需要在选择对象中添加一个选择对象。
$results = Get-ChildItems -FIlter .csv | % {
$d = Get-Date $_.Name.Substring(0,12) -Format 'M/d/yyyy'
Import-Csv $_.Name -Delimiter ',' | % {
$_ | Add-Member -Name Date -MemberType NoteProperty -Value $d -PassThru
}
}
$results
,
要执行此操作,您需要遍历文件夹中的csv文件,这些文件的名称开头应类似于'MMM d,yyyy'格式的日期。
接下来,尝试将文件名的该部分解析为DateTime对象,并将该日期添加为文件中的新第一列。
类似
# get a datetime object to use in [datetime]::TryParseExact()
$date = Get-Date
# get the csv files with a name that matches the date format 'MMM d,yyyy'
Get-ChildItem -Path 'D:\Test' -Filter '*.csv' -File |
Where-Object { $_.BaseName -match '^([a-z]{3}\s+\d{1,2},\s+\d{4})'} |
ForEach-Object {
# parse the date from the file name as captured in $matches[1]
if ([datetime]::TryParseExact($matches[1],'MMM d,yyyy',[cultureinfo]'en-US','None',[ref]$date)) {
(Import-Csv -Path $_.FullName) |
Select-Object @{Name = 'Date'; Expression = {'{0:M\/d\/yyyy}' -f $date}},* |
Export-Csv -Path $_.FullName -NoTypeInformation
}
}
正则表达式详细信息:
^ Assert position at the beginning of the string ( Match the regex below and capture its match into backreference number 1 [a-z] Match a single character in the range between “a” and “z” (case insensitive) {3} Exactly 3 times \s Match a single character that is a “whitespace character” (any Unicode separator,tab,line feed,carriage return,vertical tab,form feed,next line) + Between one and unlimited times,as many times as possible,giving back as needed (greedy) \d Match a single character that is a “digit” (any decimal number in any Unicode script) {1,2} Between one and 2 times,giving back as needed (greedy),Match the character “,” literally \s Match a single character that is a “whitespace character” (any Unicode separator,giving back as needed (greedy) \d Match a single character that is a “digit” (any decimal number in any Unicode script) {4} Exactly 4 times )
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。