繁体   English   中英

如何将命令结果批量存储到变量中?

[英]How to store the result of a command to a variable in batch?

我正在尝试制作一个.bat文件,以根据匹配条件的行数向文本文件中添加空白行。 这是什么:

@echo
SET /a maxLineas = 50
SET cantLineasDetalle="type texto.txt | find /i /c "D01" "
SET /a cantLineasAgregar = %maxLineas% - %cantLineasDetalle%

:loop
echo. >> texto.txt
set /a cantLineasAgregar-=1
if %cantLineasAgregar% GTR 0 goto loop

问题是var“ cantLineasDetalle”没有存储我想要它执行的值。

我如何分配执行'type texto.txt'的结果? 找到/ i / c“ D01”'到变量?

在此先感谢Esteban。

如前一个答案所示,您使用FOR / F循环将命令的结果存储到变量中。

find "search" <file可能比type file | find "search"更有效 如果文件很大,请type file | find "search"

在FOR / F IN()子句中执行时,所有特殊字符必须加引号或转义。 在您的情况下,需要将管道放空,或者,如果您接受我的建议,<将需要被放空。

echo. >>file echo. >>file会在echo. >>file后面加上一行空格。 另外,使用echo(而不是echo.更为安全,但是您可能永远不会遇到echo问题。要获得没有空格的空白行,请使用echo(>>file

使用SET / A进行数学运算时,可以直接引用变量,而不必将它们括在百分数中。 它也适用于百分比。

最后,将行附加在FOR / L循环中而不是使用GOTO循环会更加有效。

@echo off
set /a maxLineas=50
for /f %%N in('find /i /c:"D01" ^<texto.txt') do set /a cantLineasDetalle=%%N
set /a cantLineasAgregar=maxLineas-cantLineasDetalle
for /l %%N in (1 1 %cantLineasAgregar%) do echo(>>texto.txt

整个脚本可以压缩为以下内容(maxLineas现在基于0)

@echo off
set /a maxLineas=50-1
for /f %%N in('find /i /c:"D01" ^<texto.txt') do for /l %%I in (%%N 1 %maxLineas%) do echo(>>texto.txt

/ f %% i在('type texto.txt | find / i / c“ D01”')中执行SET cantLineasDetalle = %% i

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM