4

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:48

I 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"
    }
}
3
  • Your regex is fine, although I'd just keep it simple and remove the .*s and end up with: ,\w(?<filename>\d{3}). Commented Sep 3, 2015 at 15:42
  • @Sam: Thanks for the validation of the RegEx. With the change, I still get the same result. I guess the issue is in the code and not the regex as I assumed. Commented Sep 3, 2015 at 17:52
  • Yea, sorry I don't know anything about powershell. Commented Sep 3, 2015 at 18:13

1 Answer 1

4

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  FALSE 

And then use $_.C3 with a different RegEx.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help and explanation, JPBlanc. I appreciate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.