问题
I have a simple CSV file with six values per row (%a-%f) The %a is text string the other values are all integers. My problem is that for values %d and %e cannot be odd and must be rounded up. Should I search for each odd integer one at a time or is there a simpler way?
My CSV file looks like this:
ww-xx-yy-zzz,1,2,3,4,5
回答1:
The following script accomplishes what you are trying to do:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Define constants here:
set "CSVFILE=data.csv" & rem (input file)
set "NEWFILE=data_new.csv" & rem (output file)
set "ROUNDEVEN=#" & rem (empty to round to odd, non-empty to round to even)
set "ROUNDUP=#" & rem (empty to round down, non-empty to round up)
if defined ROUNDEVEN (set /A ROUNDEVEN=0) else (set /A ROUNDEVEN=-1)
if defined ROUNDUP (set /A ROUNDUP=1) else (set /A ROUNDUP=0)
> "%NEWFILE%" (
for /F "usebackq eol=, tokens=1-6 delims=," %%A in ("%CSVFILE%") do (
set "TEXT=%%A"
setlocal EnableDelayedExpansion
set "ROUNDED="
for %%Z in (%%D %%E) do (
set /A VALUE=^(%%Z+ROUNDUP-ROUNDEVEN^)/2*2+ROUNDEVEN
set "ROUNDED=!ROUNDED!,!VALUE!"
)
echo(!TEXT!,%%B,%%C!ROUNDED!,%%F
endlocal
)
)
endlocal
exit /B
Here is the input CSV data of your question (file data.csv
):
ww-xx-yy-zzz,1,2,3,4,5
...and the corresponding output CSV data (file data_new.csv
):
ww-xx-yy-zzz,1,2,4,4,5
The script only works if the following conditions are fulfilled:
- the input CSV file contains exactly 6 columns; too many are simply ignored, too few may disrupt column/field mapping;
- none of the columns/fields of the input CSV data is empty;
- only the first column of the input CSV data contains text data, all the others contain integers;
- none of the integer values to round has got leading zeros;
来源:https://stackoverflow.com/questions/36193222/how-do-you-use-a-batch-to-modify-certain-columns-in-a-csv-file