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

查看:165
本文介绍了捕获输出指令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或其他任何软件,它必须是CMD
DS

推荐答案

您可以使用 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%

这是一个有!变种之间的两个新行尤其重要!^ %%我之下。

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

此外,你需要逃跑(再次使用 ^ ),它具有特殊的命令行内的所有字符意到壳体,如在此实例中的管

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的内容递增。要做到这一点在一个有点便利的方式脚本允许延迟变量扩展(即!无功!语法)。

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天全站免登陆