捕获输出命令 CMD [英] Capture output command CMD

查看:50
本文介绍了捕获输出命令 CMD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Windows XP 平台

Platform Windows XP

在编写命令文件 (.bat) 时,如何将命令的输出捕获"到变量中?

When writing a command file (.bat) how can i "catch" the output from a command into a variable ?

我想做这样的事情

SET CR='dir /tw /-c b.bat | findstr /B "[0-9]"'

但这不起作用

问候斯蒂芬

PS不,我不能下载 grep、cygwin 或任何其他软件,它必须是 CMDDS

推荐答案

您可以使用 FOR/F 并通过批处理文件中的一些循环来捕获输出:

You can use FOR /F and go through some loops inside a batch file to capture the output:

@echo off
setlocal enabledelayedexpansion
set var=
for /f "tokens=* delims=" %%i in ('dir /tw /-c b.bat ^| findstr /B "[0-9]"') do set var=!var!^

%%i

echo %var%

特别重要的是,!var!^ 和下面的 %%i 之间有两个换行符.

It is especially important that there are two newlines between !var!^ and the %%i below.

此外,您需要转义(再次使用 ^)命令行中 FOR 的所有字符,这些字符对 shell 具有特殊意义,例如本例中的管道.

Additionally you need to escape (again using ^) all characters inside the command line for FOR that have special meaning to the shell, such as the pipe in this instance.

该解决方案的工作原理是迭代命令的输出并将每一行递增地附加到 var 的内容中.为了以某种方便的方式做到这一点,脚本启用了延迟变量扩展(!var! 语法).

The solution works by iterating over the output of the command and appending each line to the contents of var incrementally. To do that in a somewhat convenient manner the script enables delayed variable expansion (the !var! syntax).

这篇关于捕获输出命令 CMD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆