批处理文件标记忽略空分隔符 [英] Batch file tokens ignore empty delimiters
问题描述
我试图加载一列从CSV文件到一个变量。我的CSV文件包含空列,以便能有 ,,
这似乎是由以下被忽略:
I am trying to load a column from a CSV file into a variable. My CSV file contains empty columns so can have ,,
which seems to be ignored by the following:
FOR /F "tokens=3 delims=," %%a in (csvfile.csv) do (
set date=%%a
echo %%a
)
所以,如果文件 csvfile.csv
包含
fred,wilma,tony, john, greg, wilber, blake
chris,,steve,deon,bryan,mark,anthony
我想结果是:
tony
steve
但我得到:
tony
deon
如果我在空列把白色的空间,预计今年确实工作。
If I put a white space in the empty column this does work as expected.
如何设置 delims
,因此它不会忽略空列?
How do I set delims
so it does not ignore empty columns?
推荐答案
为
把连续的分隔符为一体。在大多数情况下,这是有帮助的。有时不是。
for
treats consecutive delimiters as one. In most cases, this is helpful. Sometimes it is not.
所以,你必须写你行的方式,即为
可以为你打算处理的。
So you have to write your lines in a way, that for
can handle as you intended.
阅读您的文件作为一个整体的每一行,开头和结尾添加引号和替换每个,
与,
,致使
Read every line of your file as a whole, add a quote at the beginning and at the end and replace every ,
with ","
, resulting in
"chris","","steve","deon","bryan","mark","anthony"
这可以愉快地与另一解析为
。在 %%〜波浪号b
删除周围的引号。
This can happily be parsed with another for
. The tilde in %%~b
removes the surrounding quotes.
@echo off
setlocal enabledelayedexpansion
FOR /F "tokens=*" %%a in (csvfile.csv) do (
set line="%%a"
for /f "tokens=3 delims=," %%b in ("!line:,="^,"!") do echo %%~b
)
这篇关于批处理文件标记忽略空分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!