我一直在研究如何编写我需要的这个bat文件 - 而且我已经走到了尽头。不确定出了什么问题。
问题/目标:我有大量的txt文件我必须从中解析5个键值。每个文本文件的前195行本质上是我不感兴趣的垃圾。
共有5个文本文件,每个文件位于5个子目录中。 目标是将这5个键值(标记7,11,19,21和25)写入csv文件。 (每个文本文件中有5个键值中的1800个 - 为我创建的csv文件总共生成9000行)
我输入第一个for循环时写的代码失败,说明" do(此时出乎意料"
这是我第一次将函数写入bat文件,或者需要多于1个for循环。我已经在多个地方调整了我的语法,但仍然得到相同的错误。显然我错过了一些东西,但我不确定是什么。可能还有其他我尚未意识到的错误,因为我甚至无法进入我的第一个循环。
代码:
@ECHO OFF
setlocal enabledelayedexpansion
set fileout="C:\ffmpeg\fit.csv"
for /R %%f in (*.txt) do (
set THEFILE=%%f
call :setTokens
goto TheEnd
)
:setTokens
for /F "skip=195 tokens=* delims=" %%A in ('%THEFILE%') do(
set the_line=%%A
call :process_line
)
:process_line
for /F "tokens=7,11,19,21,25 delims= =:" %%a in ('%the_line%') do (
set qp=%%a
set slice=%%b
set skip=%%c
set size=%%d
set y=%%e
set OUTLINE=%qp%,",",%slice%,",",%skip%,",",%size%,",",%y%
echo %OUTLINE%>>%fileout%
)
:TheEnd
答案 0 :(得分:1)
下一段代码片段应该为您完成这项工作:
@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
set fileout="C:\ffmpeg\fit.csv"
>>"%fileout%" (
for /R %%F in (*.txt) do (
for /F "usebackq skip=195 delims=" %%A in ("%%~F") do (
for /F "tokens=7,11,19,21,25 delims==: " %%a in ("%%~A") do (
echo %%a,%%b,%%c,%%d,%%e
)
)
)
)
:TheEnd
为了完整起见,下一个代码段会在脚本中显示和修复(大多数)明显的错误(请参阅下面的所有rem
条评论):
@ECHO OFF
SETLOCAL EnableExtensions EnableDelayedExpansion
set fileout="C:\ffmpeg\fit.csv"
for /R %%f in (*.txt) do (
rem strip ↓ incidental surroundig doble quotes (be on the safe side)
set "THEFILE=%%~f"
call :setTokens
rem `goto TheEnd` here would end the %%f loop just after the 1st iteration
)
rem next goto moved from inside `for /R` body
goto TheEnd
:setTokens
rem ↓↓↓↓↓↓↓↓ ↓ quotes ↓ ↓ ↓ space
for /F "usebackq skip=195 delims=" %%A in ("%THEFILE%") do (
rem removed `tokens=*` ↑ as `delims=` suffices
set "the_line=%%~A"
call :process_line
)
rem return from subroutine
goto :eof
:process_line
rem order of delimiters ↓↓↓ ↓ ↓ quotes
for /F "tokens=7,11,19,21,25 delims==: " %%a in ("%the_line%") do (
set qp=%%a
set slice=%%b
set skip=%%c
set size=%%d
set y=%%e
rem note that all `,",",` denoted below are taken literally
rem ↓↓↓↓↓ ↓↓↓↓↓ ↓↓↓↓↓ ↓↓↓↓↓
set OUTLINE=%qp%,",",%slice%,",",%skip%,",",%size%,",",%y%
rem echo %OUTLINE%>>%fileout%
rem you need to apply delayed expansion as follows:
set OUTLINE=!qp!,!slice!,!skip!,!size!,!y!
echo !OUTLINE!>>%fileout%
rem ↑↑↑↑↑↑↑↑↑↑↑ redirection could be moved
rem ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ and lopp variables used directly
rem >>"%fileout%" echo %%a,%%b,%%c,%%d,%%e
)
rem return from subroutine
goto :eof
:TheEnd
资源(必读,不完整):
%~G
等特殊页面)Command Line arguments (Parameters) >>
,2>&1
等特殊页面)Redirection