Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trim object contents in csv import

Tags:

powershell

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

like image 728
ATek Avatar asked Jun 19 '13 00:06

ATek


3 Answers

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()}  
}
like image 162
Shay Levy Avatar answered Oct 14 '22 03:10

Shay Levy


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.

like image 40
JPBlanc Avatar answered Oct 14 '22 05:10

JPBlanc


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 
}
like image 38
Red-Beard Avatar answered Oct 14 '22 03:10

Red-Beard