如何使用批处理修改CSV文件中的某些列?
我有一个简单的CSV文件,每行六个值(%a-%f) %a是文本字符串,其他值都是整数. 我的问题是,对于值%d和%e不能为奇数,必须将其四舍五入. 我应该一次搜索一个奇数整数,还是有一种更简单的方法?
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?
我的CSV文件如下:
ww-xx-yy-zzz,1,2,3,4,5
ww-xx-yy-zzz,1,2,3,4,5
以下脚本完成了您想要做的事情:
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
这是您的问题(文件data.csv
)的输入CSV数据:
Here is the input CSV data of your question (file data.csv
):
ww-xx-yy-zzz,1,2,3,4,5
...以及相应的输出CSV数据(文件data_new.csv
):
...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:
- 输入的CSV文件正好包含6列;简单地忽略了太多,太少可能会破坏列/字段映射;
- 输入的CSV数据的列/字段都不为空;
- 仅输入CSV数据的第一列包含文本数据,其他所有列均包含整数;
- 要舍入的整数值中没有一个前导零;