问题
I'm trying to split the values of a csv file into separate lines using the delimiter=, as a point to split from. i.e.
#csv file
video1,video2,video3
video4,video5,video6
#Preferred output:
video1,
video2,
video3,
ect....
So far I have:
@echo off
setLocal EnableDelayedExpansion
for /f "tokens=* delims=, " %%a in (input.csv) do (
set /a N+=1
echo ^%%a^,>>output.csv
)
However I run into the issue of parameter %%a just being added as a string. How would I cause a split instead for each , and put the string onto a newline?
回答1:
@echo off
setLocal
for /f "delims=" %%a in (input.csv) do (
for %%i in (%%a) do echo %%i,>>output.csv
)
Each line is placed into %%a
in turn.
Using the default list delimiters (space, comma, semicolon) the %%i
for assigns each token in turn from the line in %%a
to %%i
回答2:
This version can also handle empty columns and columns containing stuff like *
or ?
.
@echo off
setLocal EnableDelayedExpansion
for /f "delims=" %%a in (input.csv) do (
set "line=%%a"
echo reading line: !line!
for /F "delims=" %%C in (""!line:^,^=^"^
"!"^") do (
set "col=%%~C"
echo - !col!
)
)
The trick is, that the ; will be replaced with "<newline>"
and quotes are added to the front and end of the line.
video1,,video3
will be changed to
"video1"
""
"video3"
The %%~C
removes the outer quotes, to retrieve the desired column content
来源:https://stackoverflow.com/questions/40383897/split-values-into-separate-lines-for-each-delimiter-batch