Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

how to parse a csv file using batch script?

I'm pretty new with batch files. Can someone please help me to write a batch script that will parse a csv file that looks like this:

"Expert Info (Chat/Sequence): GET /?password=Katy HTTP/1.1
","Feb 20, 2014 19:34:46.571807000","b5:54:f4:v7:xo:6l"

"Expert Info (Chat/Sequence): GET /?password=Cory HTTP/1.1
","Feb 20, 2014 19:34:51.671167000","b5:54:f4:v7:xo:6l"

"Expert Info (Chat/Sequence): GET /?password=Mike HTTP/1.1
","Feb 20, 2014 19:34:57.145898000","b5:54:f4:v7:xo:6l"

and turn it to a another csv file that looks like this:

"Katy", "2014-02-20", "19:34:46", "b5:54:f4:v7:xo:6l" 
"Cory", "2014-02-20", "19:34:51", "b5:54:f4:v7:xo:6l" 
"Mike", "2014-02-20", "19:34:57", "b5:54:f4:v7:xo:6l"

here is what I wrote:

@echo off
FOR /F "tokens=6,8,9,10,11* delims=,? " %%a in (file.csv) do (

set pass=%%a
set month=%%b
set day=%%c
set year=%%d
set sec=%%e
set mac=%%f
echo "%%a" %%b %%c %%d %%e %%f

if %month:~1,10%==Jan set month=01
if %month:~1,10%==Feb set month=02
if %month:~1,10%==Mar set month=03
if %month:~1,10%==Apr set month=04
if %month:~1,10%==May set month=05
if %month:~1,10%==Jun set month=06
if %month:~1,10%==Jul set month=07
if %month:~1,10%==Aug set month=08
if %month:~1,10%==Sep set month=09
if %month:~1,10%==Oct set month=10
if %month:~1,10%==Nov set month=11
if %month:~1,10%==Dec set month=12

echo "%pass:~9,4%", "%year%-%month:~1,10%-%day%", "%sec:~,8%", %mac% >> text.csv)
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The simplest way to convert one data into another, like a month name into a month number, is using an array:

@echo off
setlocal EnableDelayedExpansion

rem Create the conversion array of month names to month numbers
set m=100
for %%a in (Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec) do (
   set /A m+=1
   set month["%%a]=!m:~1!
)

(for /F "tokens=6,9,10,11,12,14 delims==,. " %%a in (file.csv) do (
   echo "%%a", "%%d-!month[%%b]!-%%c", "%%e", %%f
)) > text.csv

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...