简体   繁体   English

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

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

I'm tryng to make a .bat file to add blank lines to a text file, based on the amount of lines that match a condition. 我正在尝试制作一个.bat文件,以根据匹配条件的行数向文本文件中添加空白行。 This is what a have: 这是什么:

@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

The trouble is that var "cantLineasDetalle" isn't storing the value that I want it to do. 问题是var“ cantLineasDetalle”没有存储我想要它执行的值。

How do I asign the result of the execution of 'type texto.txt | 我如何分配执行'type texto.txt'的结果? find /i /c "D01"' to a variable? 找到/ i / c“ D01”'到变量?

Thanks in advance, Esteban. 在此先感谢Esteban。

As the previous answer indicated, you use a FOR /F loop to store the results of a command into a variable. 如前一个答案所示,您使用FOR / F循环将命令的结果存储到变量中。

find "search" <file can be significantly more efficient than type file | find "search" find "search" <file可能比type file | find "search"更有效 type file | find "search" if the file is large. 如果文件很大,请type file | find "search"

When executed within a FOR /F IN() clause, all special characters must be either quoted or escaped. 在FOR / F IN()子句中执行时,所有特殊字符必须加引号或转义。 In your case the pipe will need to be escaped, or if you take my suggestion, the < will need to be escaped. 在您的情况下,需要将管道放空,或者,如果您接受我的建议,<将需要被放空。

echo. >>file echo. >>file will append a line with a space to the file. echo. >>file会在echo. >>file后面加上一行空格。 Also, it is safer to use echo( instead of echo. , but you will probably never run into a problem with echo. To get a blank line without a space use echo(>>file 另外,使用echo(而不是echo.更为安全,但是您可能永远不会遇到echo问题。要获得没有空格的空白行,请使用echo(>>file

When using SET /A to do math, you can refer to variables directly without enclosing them in percents. 使用SET / A进行数学运算时,可以直接引用变量,而不必将它们括在百分数中。 It also works with the percents. 它也适用于百分比。

Lastly, it is much more efficient to append the lines within a FOR /L loop instead of using a GOTO loop. 最后,将行附加在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

The entire script could be compressed to the following (maxLineas is now 0 based) 整个脚本可以压缩为以下内容(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