批处理文件从文本文件中读取行,其中可能包含其他文件的引用

时间:2013-07-23 12:01:39

标签: windows batch-file cmd text-files

我有一些包含一些SVN路径的文本文件。这些文本文件还将包含一些其他文本文件的引用,该文件将包含SVN路径,并且可能包含对其他文本文件的引用。

让我们看看下面的例子:

text1.txt

http://svnlink1
http://svnlink2
#file#>reference_txt1.txt
#file#>reference_txt2.txt

reference_txt1.txt

http://svnlink3
http://svnlink4
http://svnlink5
http://svnlink6

reference_txt2.txt

http://svnlink7
http://svnlink8
#file#>reference_txt3.txt

此处 text1.txt 是我的基本文件,其中包含2个SVN链接和2个其他文本文件的引用。

我想要的只是将其中任何文件中引用的所有文件的SVN链接写入其他文件,如 output.txt

请询问问题是否清楚或需要更多细节。

我尝试了什么

@echo off

cd C:\Users\user\Desktop\
C:

:readLine
for /f "tokens=*" %%a in (text1.txt) do call :processline %%a

pause
goto :eof

:processline
set line=%*
IF line contains #file#> (
call:readLine %line%
)
ELSE (
echo %line% >> output.txt
)
goto :eof

:eof

2 个答案:

答案 0 :(得分:4)

试试这个。它实现了文件读取过程process的递归调用:

@ECHO OFF &SETLOCAL
SET "startfolder=."
SET "ofile=output.txt"
CD /d "%startfolder%"
TYPE NUL>"%ofile%"
CALL :process "text1.txt"
ECHO done.
TYPE "%ofile%"
GOTO :eof

:process
SETLOCAL
FOR /f USEBACKQ %%a IN ("%~1") DO (
    FOR /f "tokens=1*delims=>" %%b IN ("%%a") DO (
        IF NOT "%%c"=="" (
            CALL :process "%%c"
        ) ELSE (
            >>"%ofile%" ECHO(%%a
        )
    )
)
ENDLOCAL
goto:eof

测试:

>type text1.txt reference_txt?.txt

text1.txt


http://svnlink1
http://svnlink2
#file#>reference_txt1.txt
#file#>reference_txt2.txt

reference_txt1.txt


http://svnlink3
http://svnlink4
http://svnlink5
http://svnlink6

reference_txt2.txt


http://svnlink7
http://svnlink8
#file#>reference_txt3.txt

reference_txt3.txt


http://svnlink9
http://svnlink10
http://svnlink11
http://svnlink12

>script.bat
done.
http://svnlink1
http://svnlink2
http://svnlink3
http://svnlink4
http://svnlink5
http://svnlink6
http://svnlink7
http://svnlink8
http://svnlink9
http://svnlink10
http://svnlink11
http://svnlink12

答案 1 :(得分:0)

您必须引用字符串并转义特殊字符,如>,这是重定向标准输出的特殊字符。

@echo off

cd C:\Users\user\Desktop\
C:
call :readline text1.txt
goto :eof

:readLine
for /f "tokens=1,2 delims=^>" %%a in (%1) do call :processline %%a %%b
pause
goto :eof

:processline
if %2.==. (
    echo %line% >> output.txt
) else (
    if %1=="#file#" call :readLine %2
)
goto :eof