Remove space from last column in comma separated csv file with package

This script removes the space from all columns

Setlocal enabledelayedexpansion
Set in=f1.csv
Set out=f2.csv
For /f "tokens=* delims=," %%A in ('type %in%') do set line=%%A
>>%out% echo !line: =!
)

Input: "a, bcd, e" Actual: "a, BCD, e" Expected: "a, bcd, e"

I want to remove only the space from the last column.

+4
source share
3 answers

!line: =!removes all spaces from a variable !line!, so you get a,bcd,e.

If you want to remove only one trailing space from the entire row, you can do this as follows:

>>%out% echo !line:~0,-1!

If you want to remove spaces in some columns and leave spaces in other columns, you will have to handle each separately.

For /f "tokens=1-3 delims=," %%A in ('type %in%') do (
    set "colA=%%A"
    set "colB=%%B"
    set "colC=%%C"
    >>%out% echo !colA!,!colB!,!colC: =!
)

This, however, will still remove all spaces from the last column.

+1

>>%out% echo !line: =!

:

if "!line:~-1"==" " set "line=!line:~0,-1"
>>%out% echo !line!

( - , )

+1

. CSV ( 20 , for /L ). call , .

@echo off & setlocal

rem // redirect output to new csv file
>"new.csv" (

    rem // get each line from the old csv file
    for /f "usebackq delims=" %%I in ("test.csv") do (
        set "line=%%I"

        rem // get the last column (max 20 columns)
        call set "last=%%line:*,=%%"
        for /L %%# in (1,1,19) do call set "last=%%last:*,=%%"

        rem // remove spaces in last column and reassemble line
        call call set "line=%%%%line:%%last%%=%%last: =%%%%%%"

        rem // output result
        setlocal enabledelayedexpansion
        echo(!line!
        endlocal
    )
)

, , CSV .

@RB: CSV PowerShell , . , - , . script + PowerShell <. > .

<# : batch portion
@echo off & setlocal

set "csvfile=test.csv"
>"new.csv" powershell -noprofile "iex (${%~f0} | out-string)"

goto :EOF
: end batch / begin PowerShell hybrid code #>

# because csv is headerless, specify generic header row (max 20 cols)
$csv = import-csv $env:csvfile -header (1..20)

# check which columns have data
$cols = $csv | gm | ?{
    $_.MemberType -eq 'NoteProperty' -and $_.Definition -match '^string'
} | %{ $_.Name }

# for each row...
for ($i=0; $i -lt $csv.length; $i++) {

    # copy meaningful column values into temporary array
    $output = @()
    foreach ($col in $cols) { $output += $csv[$i].$col }

    # replace spaces in the last element
    $output[$output.length-1] = $output[$output.length-1] -replace " "

    # output the result
    $output -join ","
}
+1
source

All Articles