2015-02-09 247 views
0

我有只有一行的txt下一个文件:如何在Windows批处理文件中读取以逗号分隔的文本文件?

1,2,3,4,5,6,...,N

我需要捕获所有用逗号隔开的数字。

+0

这可能会回答你的问题:http://stackoverflow.com/questions/134001/how-can-i-load-the-contents-of -a-text-file-into-a-batch-file-variable – Kevin 2015-02-09 18:22:43

+0

是的,但它是与一个固定的文件 – 2015-02-09 18:26:33

+0

在我的情况下,“数字”的数量可能会有所不同 – 2015-02-09 18:27:05

回答

3
@echo off 
setlocal 

set /P "numbers="<csvfile 

for %%I in (%numbers%) do (
    echo %%I 
) 

不带开关的for命令使用逗号,分号,空格和制表符作为分隔符。在上面的例子中,%%I将依次是从左到右的每个数字。

+2

'+ 1'只要线路长度不超过1021字节,它就会工作。您可以使用FOR/F来读取行,但是行长限制会增加到少于8191字节。 – dbenham 2015-02-09 19:35:29

+0

为了澄清,dbenham正在谈论'set/P“numbers =” rojo 2015-02-09 19:43:13

+0

@dbenham - 你已经找到了一个关于'+ 1'的解决方法:-) – npocmaka 2015-02-09 21:00:06

3
@echo off 
    setlocal enableextensions enabledelayedexpansion 

    rem Variable to hold digits while reading numbers 
    set "number=" 
    rem Variable to hold the table index where data is captured 
    set "n=0" 

    rem Decompose input file in characters and filter 
    for /f %%a in (' 
     cmd /q /u /c "type numbers.txt&echo(," ^| more ^| findstr /r /x /c:"[0-9,]" 
    ') do if "%%a"=="," (
     rem If a comma is found, capture current number 
     if defined number set /a "numbers[!n!]=!number!", "n+=1" 
     set "number=" 
    ) else (
     rem If it is not a comma, is a number to concatenate to current one 
     set "number=!number!%%a" 
    ) 

    rem Show numbers captured 
    set numbers[ 

这将“捕获”每个值到数组的元素。由于全部数据必须通过for命令加载到内存中,并且输入文件中的每个有效字符都将包含CRLF结尾,输入行中的限制约为715 MB。

+0

'+ 1'我经常忘记这个unicode技巧。这很好,但如果处理一个大的数据集,它会很慢。 – dbenham 2015-02-09 19:59:30

3

rojo为相对较小的数据集显示了一个很好的解决方案。

MC ND为大数据集显示了一个很好的纯批处理解决方案,除非它可能变得非常慢。

大型数据集的一个很好的快速解决方案需要使用非纯批处理。其中一个选项是我的JREPL.BAT utility,这是一个混合的JScript /批处理脚本,可以对文本执行正则表达式替换。

假设JREPL.BAT某处在您的PATH,和你的CSV是“test.csv”,那么下面会打印出每个数字,每行一个:

jrepl "," "\n" /x /f "test.csv" 

由于JREPL是一个批处理脚本如果您想在另一个批处理脚本中使用它,则必须使用CALL JREPL

下面显示了如何将数字存储在变量的“数组”中,使用FINDSTR建立数组索引。请注意,我不需要call jrepl因为jrepl是一种在(“”)中使用的条款:

@echo off 
setlocal enableDelayedExpansion 

:: Store the numbers in an array 
for /f "tokens=1,2 delims=:" %%A in (
    'jrepl "," "\n" /x /f "test.csv" ^| findstr /n "^"' 
) do (
    set "n[%%A]=%%B" 
    set "n.count=%%A" 
) 

:: Display the numbers 
for /l %%N in (1 1 %n.count%) do echo !n[%%N]! 

或者你可以使用JREPL解析出号码,并建立索引值。这需要更多的代码,但效率更高:

@echo off 
setlocal enableDelayedExpansion 

:: Store the numbers in an array 
for /f "tokens=1,2 delims=:" %%A in (
    'jrepl "\d+" "(n+=1)+':'+$0" /jmatch /jbeg "var n=0" /f "test.csv"' 
) do (
    set "n[%%A]=%%B" 
    set "n.count=%%A" 
) 

:: Display the numbers 
for /l %%N in (1 1 %n.count%) do echo !n[%%N]! 
相关问题