如何从Powershell中的csv文件列表中复制日期模式? [英] How do I grep a date pattern from a list of csv files in powershell?

查看:39
本文介绍了如何从Powershell中的csv文件列表中复制日期模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在目录中有一个文件列表,具有不同的日期,例如:

I have a list of files in a directory with different dates as such:

1. test_2017-01-01.csv
2. test_2017-02-01.csv
3. test_2017-03-01.csv
4. test_2017-04-01.csv

比方说,我想将所有文件放入标记为 $ files 的新列表中,该列表仅保存2017年1月1日至2017年3月1日期之间的文件.我将如何处理?我现在可以像这样从目录中拉出:

Let's say I want to pull all the files into a new list labeled $files that holds only files between the dates of 2017-01-01 and 2017-03-01. How would I go about this? I Can pull from the directory at the moment as such:

$files = Get-ChildItem "my_directory" | Sort-Object

推荐答案

不确定是否可以轻松将其转换为日期格式查询.您认为正则表达式在这种情况下会为您工作吗?

not sure this can be easily transformed to date format query. Do you think regex would work for you in this case?

$files = Get-ChildItem | Where-Object {$_.Name -match "^test_2017-0[123]{1}-01.csv$"}

有一线很长,但是它可以满足您的要求-将文件名中的数字字符串(必须为yyyy-MM-dd格式)转换为日期,然后评估其是否在范围内指定.

There is quite some long one-liner, but it does what you are after - converts the numeric string in the name of file (has to have format of yyyy-MM-dd) to date and then evaluates whether it's in range specified.

$files = Get-ChildItem | Where-Object {($_.Name -match "[\d]{4}-[\d]{2}-[\d]{2}") -and ([datetime][regex]::Match($_.Name, "[\d]{4}-[\d]{2}-[\d]{2}").Value -ge (Get-Date 2017/01/01)) -and ([datetime][regex]::Match($_.Name, "[\d]{4}-[\d]{2}-[\d]{2}").Value -le (Get-Date 2017/03/01))}

这篇关于如何从Powershell中的csv文件列表中复制日期模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆