Reputation: 63
How can I save the out put of a batch file to a text file and the output should be displayed on console too.
For Eg:
@ECHO OFF
ECHO Hello World
@pause
It will show Hello World on console
@ECHO OFF
ECHO Hello World >text.txt
@pause
It will save Hello World to text.txt
How can I make it both happen together?
Thanks in advance
Upvotes: 3
Views: 16791
Reputation: 613
If you want to get the outputs of commands:
if exist "file.txt" del file.txt /f /q
for /f "delims=" %%k in ('command here') do (
echo %%k
echo %%k>>file.txt
)
>>
. Don't use >
. >
would remove all the text in the file, then write the first output-ed line in the command, which is not good if there were multiple lines that will be "echo-ed" by FOR
. >>
creates a new line instead of replacing the line like >
.DELIMS=
works like TOKENS=*
, but DELIMS=
won't include the executed command.I added if exist "file.txt" del file.txt /f /q
, in order to not append the new output-ed lines. You can remove that if you want to append the lines to the file.
For customized ECHO
outputs,
@echo off
echo TEXTHERE & echo TEXTHERE >>file.txt
echo TEXTHERE2 & echo TEXTHERE >>file.txt
rem ...and so on
<command1> & <command2>
means "do <command1>
, then do <command2>
">
instead of >>
.Upvotes: 0
Reputation: 93
Use 'FOR' command if you want: (yea this one only execute 1 command)
For /f "tokens=*" %%a in ('ECHO Hello world') do (
echo %%a
echo %%a >text.txt
)
But the solution below only useful if you want to send both output to console and file a command that show a lots of texts like 'SET' command.
So what about you create an external batch file then use it in your main file?
Example: Code for 'printBoth.bat'
@echo off
setlocal ENABLEDELAYEDEXPANSION
set string=
:loop
set string=!string!%1
shift
if not "%1"=="" goto loop
For /f "tokens=*" %%a in ('!string!') do (
echo %%a
echo %%a >text.txt
)
Now if you want to print to both console and file, just type this code: call printBoth.bat [type command in here]
Upvotes: 0