我正在尝试导入和处理CSV。 从第三列的2-4位,我想将该行写入具有该标识符的文件。
作为一个例子,从第1行的“results.csv”我试图写一个名为“274.txt”的文件匹配行:
10.121.8.84,TRUE,N274SECX9010C5D,3/20/2015 15:48我有点肯定我的正则表达式可能是错的。 它看起来很好,并且能够在Expresso中查看示例文本。 但是,当添加到脚本时,我没有看到任何结果。
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代码:
$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" } }I'm trying to import and process a CSV. From the position 2-4 of the third column, I want to write that line to a file with that identifier.
As an example, from line 1 for "results.csv" I am trying to write to a file named "274.txt" the matching line:
10.121.8.84,TRUE,N274SECX9010C5D,3/20/2015 15:48I am somewhat certain my regex maybe wrong. It looks fine and is able to go through sample text in Expresso. However, when added to script, I do not see any results.
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:
$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" } }最满意答案
您应该只使用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" } }因为import-csv的结果给出了对象的结果,而不是你要在正则表达式中解析的内容。 您还可以尝试以下方法:
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然后使用$_.C3与不同的RegEx。
You should just replace your Import-Csv by Get-Content
$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. 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 FALSEAnd then use $_.C3 with a different RegEx.
更多推荐
发布评论