McVitas
McVitas

Reputation: 302

Powershell import-csv - automatically recognize delimiter?

so I work with some CSV files generated on different places. For example server has different regional settings then my laptop so the file can be delimited by , or ; If I don't specify -delimiter parameter it seems that powershell is simply unable to see that the CSV file is delimited via , so yes use that! I want to have a universal script which does not care about the CSV file origin. Seems like the only way to properly import a CSV file when you don't know the delimiter is something like this:

$line=gc "list1.csv"|select -first 1
if($line-like "*,*" -and -not ($line-like "*;*")){
    $list1=Import-Csv "list1.csv" -Delimiter ","
}else{
    $list1=Import-Csv "list1.csv" -Delimiter ";"
}

Anybody has a better idea?

Upvotes: 3

Views: 2207

Answers (2)

Peter Kay
Peter Kay

Reputation: 996

You could easily make it much readable using a switch in PowerShell

There's nothing on PowerShell that would automatically determine the delimiter. You could create a function that can do this with the following switch statements:

$a = $line -like "*,*"
$b = $line -like "*;*"

switch($True) {
  $a    {Import-Csv "list.csv" -Delimiter ","}
  $b    {Import-Csv "list.csv" -Delimiter ";"}
  Default {Write-Error "Cannot determine delimiter"}
}

Although, if there are different delimiters you want to add in, you would have to work out the logic. That, I leave up to you to do :).

Upvotes: 1

Fourat
Fourat

Reputation: 2447

Not so better idea, just refactoring :

$line = Get-Content "list1.csv" | Select -First 1
$delimiter = if($line.Split(";").Length -gt 1){";"}else{","};
$list1 = Import-Csv "list1.csv" -Delimiter $delimiter

Of course this works only if your delimiter is , or ;.

Upvotes: 3

Related Questions