如何将FOR循环输出到批处理文件中的变量中

时间:2010-10-28 15:44:21

标签: batch-file

我有一个这样的文件,需要解析并需要提取版本号。

[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible 
[assembly: AssemblyFileVersion("0.4.2")]
...
...

我需要解析它并从中提取0.4.2

我必须在Windows批处理文件中执行此操作。我通过以下方式做到了这一点,但我知道这是最好的方式。

setlocal enabledelayedexpansion
SET VERSIONSTR=

REM This is an ugly way to do this, because due to some reason I cant save output of for loop to a variable
REM I would like this in a variable instead of a temp file.
FOR /f "tokens=2*" %%j in (AssemblyInfo.cs) do  @echo %%j  >> tempfile.txt

REM The "AssemblyFileVersion" line has the version number.
REM I would like this in a variable instead of a temp file.
FOR /f %%i in (tempfile.txt) do @echo %%i | find "AssemblyFileVersion" >> anothertempfile.txt

REM Now this for loop will set a variable.
FOR /f %%k in (anothertempfile.txt) do set VERSIONSTR=%%k

REM Now the line is `AssemblyFileVersion("0.4.2")]` so, I am getting the substring from 21st character
REM till the end and then removing last 3 characters, getting us the string 0.4.2
SET VERSIONSTR=!VERSIONSTR:~21,-3!

我讨厌在我的代码中出现这种丑陋,有关如何修改此问题的任何想法?至少我想知道一种方法让我在windows批处理文件中的变量中获得for循环的输出。

1 个答案:

答案 0 :(得分:0)

for /f "tokens=2 delims=()" %%a in ('findstr AssemblyFileVersion AssemblyInfo.cs') do set Version=%%~a
echo %Version%

它有点难看因为我不能(显然)使用引号作为分隔符,所以我选择了括号并删除了引号%%~x。顺便说一句,你可以在这里避开所有临时文件。

上面的代码只是直接抓取相应的行(findstr)并使用for /f对其进行标记。