Monday, March 1, 2010

Importing a TSV

I have been playing around a bit today with .tsv files (Tab Seperated).  Most of the time this would simply be a matter of using import-csv filename.csv.  Well, what happens when the header row has spaces or special characters, or you have no header row?  Create one.

CODE

$data = @()
$list = gc file.tsv

foreach ($line in $list) {
    $row = "" | Select One,Two,Three,Four,Five
    $row.One = ($line.Split("`t"))[0]
    $row.Two = ($line.Split("`t"))[1]
    $row.Three = ($line.Split("`t"))[2]
    $row.Four = ($line.Split("`t"))[3]
    $row.Five = ($line.Split("`t"))[4]
    $data += $row
}
 code: copy : expand : collapse
EXPLANATION
I have used $row = "" | Select One,Two,Three,Four,Five to create headers called One,Two..., but these can be renamed to anything a bit more meaning full. Remember, no space or special characters. That was the original point of this. Once the header is created then we simply use the .Split() method to create an array of strings from each line. Simple enough!

2 comments:

Anonymous said...

Look at you picture. It's broken and confusing. It has nunerous odd characters in most browsers.

Anonymous said...

I'm not sure what you mean. With my IE7, IE8, and FireFox I see no problems. Could you please be more specific so I can correct the problem?