views:

143

answers:

3

I have a text file which contains several lines, each of which is a comma separated string. The format of each line is:

<Name, Value, Bitness, OSType>

Bitness and OSType are optional.

For example the file can be like this:

Name1, Value1, X64, Windows7
Name2, Value2, X86, XP
Name3, Value3, X64, XP
Name4, Value3, , Windows7
Name4, Value3, X64 /*Note that no comma follows X64 */
....
....

I want to parse each line into 4 variables and perform some operation on it. This is the PowerShell script that I use..

Get-Content $inputFile | ForEach-Object {
    $Line = $_;

    $_var = "";
    $_val = "";
    $_bitness = "";
    $_ostype = "";

    $envVarArr = $Line.Split(",");
    For($i=0; $i -lt $envVarArr.Length; $i++) {
        Switch ($i) {
            0 {$_var = $envVarArr[$i].Trim();}
            1 {$_val = $envVarArr[$i].Trim();}
            2 {$_bitness = $envVarArr[$i].Trim();}
            3 {$_ostype = $envVarArr[$i].Trim();}
        }                                    
    }
    //perform some operation using the 4 temporary variables
}

However, I wanted to know if it is possible to do this using regex in PowerShell. Would you please provide sample code for doing that? Note that the 3rd and 4th values in each line can be optionally empty.

+2  A: 

Wouldn't it be better to use Import-Csv which does all this (and more reliably) for you?

Tim Pietzcker
And if you already have a line of CSV you can pipe it to `ConvertFrom-Csv` to turn it into an object. Both commands let you specify a custom delimiter too.
Josh Einstein
+2  A: 

As Tim suggests, you can use use Import-Csv. The difference is that Import-Csv reads from a file.

@"
Name1, Value1, X64, Windows7
Name2, Value2, X86, XP
Name3, Value3, X64, XP
Name4, Value3, , Windows7
Name4, Value3, X64 /*Note that no comma follows X64 */
"@ | ConvertFrom-Csv -header var, val, bitness, ostype

# Result

var   val    bitness                                 ostype  
---   ---    -------                                 ------  
Name1 Value1 X64                                     Windows7
Name2 Value2 X86                                     XP      
Name3 Value3 X64                                     XP      
Name4 Value3                                         Windows7
Name4 Value3 X64 /*Note that no comma follows X64 */         
Doug Finke
+3  A: 

You can specify an alternate column header row for the imported file file with the -Header parameter of the Import-Csv cmdlet:

Import-Csv .\test.txt -Header Col1,Col2,Bitness,OSType
Shay Levy