Let’s say you’ve got a huge CSV-fomatted file and you want to pull a particular element out some other processing. In the past you might have read the file into Excel and used the text-to-column feature to parse the elements. This can be accomplished much quicker and easier in Powershell:

Technique 1: parse using the “split” function:
Here we will split the CSV elements from each line and output the 2nd element (remember that arrays start at zer so an index of  is the 2nd element)

?View Code POWERSHELL
#long version
get-contet myfile.csv|foreach {$_.split(",")[1]}
#short version
gc myfile.csv|% {$_.split(",")[1]}

Technique 2: parse with selection criteria
Here we want to exclude the header row from our CSV file:
Simply add the “where-object” cmdlet t to the pipeline and specify your selection critera

?View Code POWERSHELL
#long version
get-contet myfile.csv|where-object -notlike "*element1,element2*"|foreach {$_.split(",")[1]}
#short version
gc myfile.csv|? -notlike "*element1,element2*"|% {$_.split(",")[1]}

But wait, there’s more!

Technique 3: use import-csv:
Provided that your CSV data has a header row describing the content of each element, you can use the import-csv cmdlet

To see what the data elements (aka “properties”) are, use the get-member cmdlet

?View Code POWERSHELL
#long version
import-csv myfile.csv | get-member
#short version
ipcsv  myfile.csv | gm

Once you know which element you are looking for, use the select-object cmdlet

?View Code POWERSHELL
#long version
import-csv myfile.csv | select-object "element-2"
#short version
ipcsv myfile.csv | select "element-2"

  2 Responses to “How to Parse CSV data”

  1. I have a file full of last-names separated by commas and then first-names.
    Smith,Bob
    Chicken,Ronald
    Car,Anastasia

    I’d like to grab the first character of the first name and then pre-pend it to the string of the last name.

    How can I even have the last name print out before the first name on one line and on the next have the same thing?

  2. Let’s say that your file is named “names.txt”

    Here’s how you can reformat the data as First Letter of First Name + Last Name :

    gc names.txt | % {$_.split(“,”)[1][0] + $_.split(“,”)[0]}

    here’s the output:

    BSmith
    RChicken
    ACar

    Explanation:

    gc = get-content from the file

    then pipe to the split method (parsed by comma)
    $_.split(“,”)[1][0] = get first letter of the first name
    $_.split(“,”)[0] = get the entire last name

    use the plus “+” operator to concatenate the two name elements

    hopefully this makes sense

    good luck!

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

   
© 2011 Posh TipsSuffusion theme by Sayontan Sinha

Page optimized by WP Minify WordPress Plugin