Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

replace string in csv file using batch file

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...