簡體   English   中英

批處理文件將多個文件中的文本合並到一個csv中

[英]batch file combine text from multiple files into one csv

我在一個網站上看到了這段代碼,該代碼是從以前的堆棧溢出線程中剝離出來的,但這正是我正在嘗試使用批處理的內容。 我對批處理的工作很少,雖然看起來應該可以產生所需的最終結果,但它並沒有達到我想要的效果,因此我們將不勝感激。 在代碼下面,我舉了一個我要完成的示例。

@echo off
set local EnableDelayedExpansion

for %%f in (*.txt) do (
    set i=0
for /F "delims=" %%l in (%%f) do (
    set /A i+=1
    set line!i!=%%l
)
echo %%f, !line1!, !line2!, !line3!, >> result.csv

text file 1    text file 2    text file 3 >> output.csv
1111,          2222,          3333           1111,2222,3333
1111,          2222,          3333           1111,2222,3333
1111,          2222,          3333           1111,2222,3333
1111,          2222,          3333           1111,2222,3333
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION 
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "tempfile=%temp%\tempfile.txt"
SET "outfile=%destdir%\outfile.txt"

(
FOR %%f IN (
 q42500455_0.txt q42500455_1.txt q42500455_2.txt q42500455_3.txt q42500455_4.txt q42500455_5.txt
 ) DO FINDSTR /n /r "." "%sourcedir%\%%f"
)>"%tempfile%"

SET /a maxline=0
FOR /f "usebackqtokens=1delims=:" %%a IN ("%tempfile%") DO IF %%a gtr !maxline! SET /a maxline=%%a

(
FOR /L %%L IN (1,1,%maxline%) DO (
 SET "line="
 FOR /f "usebackqtokens=1*delims=:" %%a IN ("%tempfile%") DO IF %%a==%%L (
  SET "line=!line!%%b"
 )
 ECHO !line!
)
)>"%outfile%"

DEL "%tempfile%" >NUL 2>nul

GOTO :EOF

您需要更改sourcedirdestdir的設置以適合您的情況。

我使用了名為q42500455*.txt文件,其中包含用於測試的數據。

產生定義為%outfile%的文件

第一個for循環僅對列表中每個文件的每一行編號,然后將結果輸出到臨時文件(其名稱無關緊要)。 結果是一個包含

1:line1 from file1
2:line2 from file1
...
1:line1 from file2
2:line2 from file2
...

下一個for循環僅計算使用的最大行號,並使用:作為分隔符將行號標記為%%a

下一節將行號計入%%L ,然后從臨時文件中的匹配行號構建line 由於臨時文件按文件指定的順序包含第n行,因此選擇每行n並將它們串在一起將按照指定的方式構建該行。

請注意,我懷疑你的數據發布,其中有終端,對除了最后一個文件的每一行。 我認為,這,缺失和程序,預計插入, S作為分隔符。

如果是這樣,則所需的更改是:

...
  SET "line=!line!,%%b"
 )
 ECHO !line:~1!
...

插入逗號,然后在所有線條上echo顯第一個字符。

此方法逐個文件執行直接合並,當一個文件的行數少於其他文件時,調整行數。

@echo off
setlocal EnableDelayedExpansion

rem Set the current directory where the Batch file is
cd "%~P0"

set "comma="
del result.csv 2>NUL
for %%f in (*.txt) do (

   rem If this is the first file
   if not exist result.csv (
      rem ... just copy it
      copy "%%f" result.csv > NUL

   ) else (

      rem Merge this file with previous one
      set "comma=!comma!,"
      move /Y result.csv result.in > NUL

      rem Read lines of previous file from Stdin
      < result.in (
      rem ... and combine they with this file
      for /F "usebackq delims=" %%l in ("%%f") do (
         set "line=!comma:~1!"
         set /P "line="
         echo !line!,%%l
      )

      rem If previous file is longer than this one, copy the rest of lines
      for /F "delims=" %%l in ('findstr "^"') do echo %%l,

      rem Combine previous output in new result file
      ) > result.csv

   )
)
del result.in

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM