ATek
ATek

Reputation: 825

trim object contents in csv import

I need to run a trim method on each value extracted from the csv import object. haven't tried something like below but for me I don't want to have to define a trim command at the end of each one of my variables being passed to functions.

$csvobj = "c:\somestuff.csv"

foreach ($csvitem in $csvobj) {
$csvitem.value1.trim()
$csvitem.value2.trim()
}

Thanks in advance, SS

Upvotes: 6

Views: 17616

Answers (3)

Red-Beard
Red-Beard

Reputation: 125

Here's a slight modification of the above accepted answer. This strips all leading / tailing spaces from all .csv files in the current folder. Hope it helps!

gci -filter *.csv | foreach {
    echo $_.NAME
    $csv = Import-Csv $_.NAME
    $csv | Foreach-Object {   
        $_.PSObject.Properties | Foreach-Object { $_.Value = $_.Value.Trim() } 
    }
    $csv | Export-Csv $_.NAME -NoTypeInformation 
}

Upvotes: 1

Shay Levy
Shay Levy

Reputation: 126872

This will trim all values in the csv file and assign the result to $csv.

$csv = Import-Csv c:\somestuff.csv | Foreach-Object {
   $_.PSObject.Properties | Foreach-Object {$_.Value = $_.Value.Trim()}  
}

Upvotes: 8

JPBlanc
JPBlanc

Reputation: 72670

You can try this :

$a = import-csv "c:\somestuff.csv"
$a | % {$b=$_;$_.psobject.Properties | % {$c=$_.name ;$b."$c"=($b."$c").trim()}}

First : I import all the lines into $a.

Second : In a first loop I read each object (each CSV line), then for each object in a second loop I read each property, then I can trim each var.

Upvotes: 1

Related Questions