问题
I have a csv file with 18 fields. I need to copy the file to a txt file, delete the first four lines, replace the data in field #8, and save the file with a new name.
The data in field #8 is an integer (for example, 1, 2, 3, etc). Each integer needs to be replaced with a separate value (for example, I need to replace 1 with 1005 and 3 with 1008). I am trying to modify/fix the following batch file:
@echo off
More +4 datatest.csv > datacopy.txt
( FOR /f "tokens=8 delims=," %%h in (datacopy.txt) do (
if "%%h"=="3" (echo 1008) else (
echo %%a %%b %%c` echo %%a %%b %%c
)
)
)>paygoinvoice.txt
@echo on
回答1:
- With only one token selected, you'll get only one column (%%h)
- parsing the more command directly, there is no need for a temporary file.
- depending on how many integers to replace, you may use a pseudo array with the int as an index/pointer.
- you may either get all columns separately (
tokens=1-18
,%%A..%%R
) or gather the rest*
in one for variable.
@echo off & Setlocal EnableDelayedExpansion
( FOR /f "tokens=1-8* delims=," %%A in ('More +4 datatest.csv') do (
Set "H=%%H"
if "%%H"=="1" Set "H=1005"
if "%%H"=="3" Set "H=1008"
echo %%A,%%B,%%C,...,!H!,%%I
)
)>paygoinvoice.txt
@echo on
来源:https://stackoverflow.com/questions/53916055/replace-string-in-csv-file-using-batch-file