简体   繁体   中英

How to save output from Command prompt

I know the general syntax to save the output to a text file while executing in command prompt.

But my need is different. I want to see it in the Command prompt window also I want to save it in text file. USually using > c:\\dirlist.txt will save to text file but cant see in command prompt window.

I need to see in command prompt as well as save in text file. Any help

At first, it is relatively easy to write a TEE.BAT program. The only problem is that set /p command (used to get the output from the command) doesn't differentiate between the end of file and an empty line. This mean that the output will be captured until the first empty line (or the end of file):

@echo off
:: usage: AnyCommand | TEE filename
setlocal EnableDelayedExpansion
if exist %1 del %1
:nextLine
set line=:EOF
set /p line=
if "!line!" == ":EOF" goto :eof
echo(!line!
echo(!line!>> %1
goto nextLine

You may test that this Batch file indeed works this way:

tee CopyOfFile.txt < File.txt

However , when this Batch file is used in the way it was designed, it fails now and then:

type File.txt | tee CopyOfFile.txt

Previous line sometimes works ok and sometimes show and store just the first line of the file. I made several tests and can not isolate the cause of the error. Perhaps someone (jeb?) could explain what is happening in this case and give a solution.

You want the equivalent of the tee program for Windows. If you can use PowerShell , then you already have what you need . Otherwise, google for an implementation that works on your system.

Alternatively, you could redirect the output to a file and observe that file with a live log viewer from another command prompt (ie the equivalent of tail ).

The following is another approach for displaying and Logging command output:

@Echo off & CD "%~dp0"
For /F "UsebackQ Tokens=* Delims=" %%A in (`"%~1"`) do (
    >>Outputfile.txt Echo(%%A
    Echo(%%A
)
Goto :EOF

You can write your own tee with batch, like the one of Aacini, but without the drawbacks.

@ECHO OFF
setlocal DisableDelayedExpansion
for /F "delims=" %%A in ('findstr /n "^" ') do (
  set "line=%%A"
  setlocal EnableDelayedExpansion
  set "line=!line:*:=!"
  (echo(!line!)
  (echo(!line!) > "%~1"
  endlocal
)

The initially idea is from walid2me echo to screen and file in a single line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM