[英]RegEx & Powershell: Use Regex to Create Files based on name found in CSV
I'm trying to import and process a CSV. 我正在尝试导入和处理CSV。 From the position 2-4 of the third column, I want to write that line to a file with that identifier.
从第三列的第2-4位开始,我想将该行写入具有该标识符的文件中。
As an example, from line 1 for "results.csv" I am trying to write to a file named "274.txt" the matching line: 作为一个例子,从第1行“results.csv”我试图写一个名为“274.txt”的文件匹配行:
10.121.8.84,TRUE,N274SECX9010C5D,3/20/2015 15:48
I am somewhat certain my regex maybe wrong. 我有点肯定我的正则表达可能是错的。 It looks fine and is able to go through sample text in Expresso.
它看起来很好,并且能够在Expresso中查看示例文本。 However, when added to script, I do not see any results.
但是,当添加到脚本时,我没有看到任何结果。
Results.csv: Results.csv:
10.121.88.84,TRUE,N274SECX9610C5D,3/20/2015 15:48
10.77.89.109,TRUE,L186OFFX2K6KMX1,3/24/2015 9:49
10.144.18.135,TRUE,N488FOOD2NK6MB1,3/25/2015 7:20
10.181.92.175,FALSE,,
10.147.86.54,FALSE,,
Powershell Code: Powershell代码:
$path = Split-Path -parent $MyInvocation.MyCommand.Definition
$Results_File = $path + "\results.csv"
Import-Csv $Results_File | ForEach {
If ($_ -Match '^.*,\w(?<filename>\d{3}).*') {
$_ | Out-File -Append "$($Matches.Filename).csv"
}
}
You should just replace your Import-Csv
by Get-Content
您应该只用
Get-Content
替换Import-Csv
$path = Split-Path -parent $MyInvocation.MyCommand.Definition
$Results_File = $path + "\results.csv"
get-content $Results_File | ForEach {
If ($_ -Match '^.*,\w(?<filename>\d{3}).*') {
$_ | Out-File -Append "$($Matches.Filename).csv"
}
}
Because the result of import-csv
gives alist of objects whish is not what you want to parse in your regex. 因为
import-csv
的结果给出了对象的alist,而不是你要在正则表达式中解析的内容。 You can also try the following : 您还可以尝试以下方法:
Import-Csv $Results_File -Header 'C1','C2','C3','C4'
C1 C2 C3 C4
-- -- -- --
10.121.88.84 TRUE N274SECX9610C5D 3/20/2015 15:48
10.77.89.109 TRUE L186OFFX2K6KMX1 3/24/2015 9:49
10.144.18.135 TRUE N488FOOD2NK6MB1 3/25/2015 7:20
10.181.92.175 FALSE
10.147.86.54 FALSE
And then use $_.C3
with a different RegEx. 然后使用
$_.C3
与不同的RegEx。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.