我希望使用批处理脚本将目录中的所有CSV / TXT文件组合在一起,并希望你们可以提供帮助 - 这对于编写脚本非常新,所以如果我要求解释每行的内容,请原谅我, 我确实发现了一些有用的东西但是在测试时它仍然保留了一个标题行。我希望它会合并所有文件 - 没有标题。
供参考:
@echo off
setlocal enableextensions disabledelayedexpansion
rem configure paths
set "source=C:\Users\Khalid\Desktop\New_folder\p*.csv"
set "target=C:\Users\Khalid\Desktop\newfile.csv"
rem remove output file if needed
if exist "%target%" del "%target%" >nul 2>nul
rem search for header row
set "headerRow="
for %%f in ("%source%") do (
<"%%~ff" ( for /l %%a in (1 1 10) do if not defined headerRow set /p
"headerRow=" )
if defined headerRow goto haveHeader
)
:haveHeader
if not defined headerRow (
echo ERROR: impossible to get header row.
goto endProcess
)
rem output header to header file to use as filter.
rem header is cut to avoid findstr limitations on search strings
set "headerFile=%temp%\%~nx0_headerFile.tmp"
setlocal enableextensions enabledelayedexpansion
> "%headerFile%" echo(!headerRow:~0,125!
endlocal
rem search for input files with matching headers to join to final file
for /f "tokens=*" %%f in ('findstr /m /b /l /g:"%headerFile%" "%source%"') do (
if not exist "%target%" (
rem first file is directly copied
copy "%%~f" "%target%" /y > nul 2>nul
) else (
rem next files are filtered to exclude the header row
findstr /v /b /l /g:"%headerFile%" "%%~f" >> "%target%"
)
echo ... [%%~ff] joined to %target%
)
rem remove the temporary header file
del "%headerFile%" >nul 2>nul
:endProcess
endlocal
答案 0 :(得分:0)
一种简单的方法可能是
@echo off
setlocal enableextensions disabledelayedexpansion
rem configure paths
set "source=p*.csv"
set "target=newfile.csv"
>"%target%" (
for %%a in ("%source%") do (
set "headerRow="
<"%%~fa" (
for /l %%h in (1 1 10) do if not defined headerRow set /p "headerRow="
findstr "^"
)
)
)
对于每个输入文件,读取其标题并转储文件的其余部分。所有输出都被发送到输出文件。
请注意,此方法有一个限制:set /p
无法读取超过1021个字符,如果您的.csv
文件有更长的行,那么,按照原始方法,您可以使用类似< / p>
@echo off
setlocal enableextensions disabledelayedexpansion
rem configure paths
set "source=p*.csv"
set "target=newfile.csv"
set "headerFile=%temp%\%~nx0_headerFile.tmp"
>"%target%" (
for %%a in ("%source%") do (
set "headerRow="
<"%%~fa" (
for /l %%h in (1 1 10) do if not defined headerRow set /p "headerRow="
setlocal enableextensions enabledelayedexpansion
> "%headerFile%" echo(!headerRow:~0,125!
endlocal
)
findstr /v /b /l /g:"%headerFile%" "%%~fa"
)
)
rem remove the temporary header file
del "%headerFile%" >nul 2>nul
答案 1 :(得分:0)
如果您的文件在每个文件的第一行上都有一个行标题,并且行顺序不重要:
@Echo Off
(For %%A In ("%UserProfile%\Desktop\New_folder\p*.csv") Do More +1 "%%a")>"%UserProfile%\Desktop\newfile.csv"