Powershell - 从CSV文件的列中删除空格

时间:2017-08-11 19:40:28

标签: powershell

我有一个CSV文件,其中有一列在我需要删除的列中间有空格。以下是几行数据的示例以及我希望得到的结果。如果可能的话,我想用powershell做这件事。

电流:

"setvalue","36499","GORBEL INC","882","7/11/17","-   4989.00","R31836"
"setvalue","7047","5TH 3RD CC","19775","7/13/17","51.61",""
"setvalue","68329","J D NEUHAUSE, L.P.","56866","7/10/17","-       .12","R31838"
"setvalue","27085","MAGNETEK INC","727031","6/30/17","-   1002.57","R69706"

预期输出:

"setvalue","36499","GORBEL INC","882","7/11/17","-4989.00","R31836"
"setvalue","7047","5TH 3RD CC","19775","7/13/17","51.61",""
"setvalue","68329","J D NEUHAUSE, L.P.","56866","7/10/17","-.12","R31838"
"setvalue","27085","MAGNETEK INC","727031","6/30/17","-1002.57","R69706"

有人可以告诉我这样做的方法吗?

1 个答案:

答案 0 :(得分:0)

要引用列,它需要一个标题,所以:

$InputCSVFile=".\input.csv"
$OutputCSVfile=".\output.csv"

$headers = 1..7|%{"H{0}" -f $_}
$Csv = Import-Csv $InputCSVFile -Header $Headers
$Csv|ft -auto

ForEach ($Row in $Csv) {
     $Row.H6 = $Row.H6 -Replace ' '
}
$Csv | Export-Csv $OutputCSVfile -NoType
# to skip the header change the previous line with the following one
# $CSV | ConvertTo-CSV -NoType | Select -Skip 1 | Set-Content $OutputCSVFile

示例输出

> .\SO_45642679.ps1

H1       H2    H3                 H4     H5      H6          H7
--       --    --                 --     --      --          --
setvalue 36499 GORBEL INC         882    7/11/17 -   4989.00 R31836
setvalue 7047  5TH 3RD CC         19775  7/13/17 51.61
setvalue 68329 J D NEUHAUSE, L.P. 56866  7/10/17 -       .12 R31838
setvalue 27085 MAGNETEK INC       727031 6/30/17 -   1002.57 R69706


"setvalue","36499","GORBEL INC","882","7/11/17","-4989.00","R31836"
"setvalue","7047","5TH 3RD CC","19775","7/13/17","51.61",""
"setvalue","68329","J D NEUHAUSE, L.P.","56866","7/10/17","-.12","R31838"
"setvalue","27085","MAGNETEK INC","727031","6/30/17","-1002.57","R69706"