如何使用bat脚本将命令表达式的结果存储在变量中?

时间:2009-09-15 13:35:23

标签: batch-file

我有以下命令来计算模式20??????之后的所有目录:

'dir /b "20??????" | find /c "2"'

例如,如果我有以下目录,该命令将返回6:

20090901
20090902
20090903
20090904
20090905
20090906

如何将此命令的结果(前面提到的示例中的6)存储在变量?

5 个答案:

答案 0 :(得分:45)

set cmd="dir /b "20??????" | find /c "2" "

FOR /F "tokens=*" %%i IN (' %cmd% ') DO SET X=%%i

答案 1 :(得分:8)

(dir /b "20??????" | find /c "2")>>x.txt  
set /p variable=<x.txt

就是这样。

当然,如果您不想要该文件,请稍后执行此操作:

del x.txt

编辑 - 如何使文件名唯一:

@Mai:使用它来创建一个uniqe文件名:

set timestamp=%date:.=%%time::=%
set timestamp=%timestamp:,=%
set timestamp=%timestamp:/=%
set timestamp=%timestamp:-=%
set filename=file%timestamp%.tmp

如果系统区域的日期格式包含

中的其他字符,请添加更多替换项

答案 2 :(得分:2)

以下是一个示例:

@echo off
set wildcard=C:\*.*
set count=0
FOR /F %%a in ('DIR /B %wildcard%') do set /A count=count+1
echo %count% files matching %wildcard%
set choice=
set /p choice=Press enter to continue ...

答案 3 :(得分:0)

这是我的代码:

@echo off
set com=echo HI
::Start Of Code You Need
echo|%com%>>"%temp%\tmp.txt"
for /f "tokens=* delims=" %%x in (%temp%\tmp.txt) do (
set output=%%x
)
del /q %temp%\tmp.txt
::End Of Code You Need
echo This Is The Output:
echo %output%
pause>NUL

它取自com的输入和output

的输出

答案 4 :(得分:-2)

@echo off

REM The command fltmc volumes provides some information about drives
REM I need to extract the drive letter associated to a particular volume name.
REM Here's how:

fltmc volumes | find /i "\Device\HarddiskVolume3" > delme.txt
for /f "tokens=1 delims= " %%i in (delme.txt) DO echo %%i
Del /f delme.txt