我需要分析CSV文件列表中提供的结果,其中我需要有文件名和第二行,这是单个输出中结果目录的文件集。我在Stack Overflow上找到了一段代码来获取文件名和一段代码来获取文件的第二行。坦率地说,将它们拼凑在一起是我所不知道的。
这是我到目前为止所做的:
setlocal enabledelayedexpansion
@echo "filename secondline"
for /f "delims=" %%a in ('dir /b /s *.*') do (@echo %%~nxa
set filename=%%~a
echo %filename%
pause
for /f "tokens=1,* delims=:" %i% in ('findstr /n /r . %filename%') do(if %i% geq 2 if %i% leq 2 echo %j% )
rem pause
)
endlocal
如何将目录中所有CSV文件的文件名和第二行转换为另一个CSV文件?
答案 0 :(得分:0)
目前还不是很清楚你想要什么。所以,让我添加一些关于我理解的信息。
目录中有一些CSV文件,例如C:\Temp
,这是执行批处理文件的当前目录,其中包含例如:
<强> C:\温度\ DataFile1.csv 强>
first name,second name,address,country
John,Doe,"20 Baker Street, Nowhere",Fantasy Island
x,y,anywhere,anyland
<强> C:\温度\ DataFile2.csv 强>
first name,second name,address,country
Jane,Doe,"5 Hammer Lane, Somewhere",Happy Island
x,y,anywhere,anyland
在同一目录中,应创建一个名为ExtractionResults.csv
的CSV文件,其中包含最终的示例:
"C:\Temp\DataFile1.csv",John,Doe,"20 Baker Street, Nowhere",Fantasy Island
"C:\Temp\DataFile2.csv",Jane,Doe,"2 Hammer Lane, Somewhere",Happy Island
如果其中一个CSV文件的文件名为逗号,则应引用第一列中的文件名。
对于此类任务,可以使用以下注释的批处理文件:
@echo off
rem Name of results file without file extension with or without path.
set "ResultsFileName=ExtractionResults"
rem Delete a perhaps already existing results file from a previous run.
del "%ResultsFileName%.csv" 2>nul
rem Delete also a perhaps already existing temporary results file from
rem a not completed previous run. A temporary file with a file extension
rem different to CSV is used for the results in case of results file is
rem created also in current directory with file extension CSV. This must
rem be done to avoid that the second line of the results file is included
rem in the results, too.
del "%ResultsFileName%.tmp" 2>nul
rem Call for each CSV file in current directory the subroutine
rem GetSecondLine with full name of the CSV file.
for %%I in (*.csv) do call :GetSecondLine "%%~fI"
rem Use command MOVE instead of RENAME to rename the file in case of results
rem file name is specified at top with an absolute or relative path as the
rem command RENAME does not allow as second parameter a file name with path.
move /Y "%ResultsFileName%.tmp" "%ResultsFileName%.csv"
rem Exit this batch file and return to parent batch file or command processor.
goto :EOF
rem This is a subroutine. It prints to the temporary results file
rem just the second line or nothing if the file contains just 1 line.
rem The execution of goto :EOF results here in exiting the subroutine.
:GetSecondLine
for /F "usebackq skip=1 delims=" %%L in ("%~1") do (
echo "%~1",%%L>>"%ResultsFileName%.tmp"
goto :EOF
)
goto :EOF
嗯,上面的代码包含的注释行多于命令。但是为了更好地理解使用的命令及其工作原理,打开命令提示符窗口,执行以下命令,并完全阅读为每个命令显示的所有帮助页面。
call /?
del /?
for /?
goto /?
move /?
rem /?
另请阅读Microsoft文章Using command redirection operators,了解>>
和2>nul
的解释。