问题
I have some tool which is outputs some data directly to console output.
I want to save this output to some variable and then pass it somewhere else...
Is it possible to do?
Example:
rem this outputs String1 values from myfile.txt
GetString myfile.txt String1
rem I want this value for example in %p% variable, and then:
call MyApp %p%
回答1:
You can try this
for /f %%a in ('GetString myfile.txt') do call MyApp %%a
Although I'm not really sure what you mean about the String1
bit, if this isn't right, can you clarify?
回答2:
Generally, I would advice to follow @Balic C's answer as it works without temporary files. Nevertheless the for
command has it's issues (or at least can be hard to get right) when the command or the arguments, or both, contain spaces and you need to handle proper quoting.
In such a case you could also store the output of the tool in a temporary file and then read it into a variable using set /P
:
set temp_file=%TEMP%\%~n0.tmp
GetString myfile.txt > "%temp_file%"
set /P p=<"%temp_file%"
call MyApp %p%
del /F "%temp_file%"
来源:https://stackoverflow.com/questions/12600856/cmd-console-output-to-variable