繁体   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