2015-02-09 248 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]! 
相關問題