How do I display a text file content in CMD? - cmd

I want to display the content of a text file in a CMD window. In addition, I want to see the new lines that added to file, like tail -f command in Unix.

You can use the more command. For example:
more filename.txt
Take a look at GNU utilities for Win32 or download it:

We can use the 'type' command to see file contents in cmd.
Example -
type abc.txt
More information can be found HERE.

I don't think there is a built-in function for that
xxxx.txt > con
This opens the files in the default text editor in windows...
type xxxx.txt
This displays the file in the current window. Maybe this has params you can use...
There is a similar question here: CMD.EXE batch script to display last 10 lines from a txt file
So there is a "more" command to display a file from the given line, or you can use the GNU Utilities for Win32 what bryanph suggested in his link.

To show content of a file:
type file.txt - cmd
cat file.txt - bash/powershell

You can use the 'more' command to see the content of the file:
more filename.txt

Using a single PowerShell command to retrieve the file ending:
powershell -nologo "& "Get-Content -Wait c:\logFile.log -Tail 10"
It applies to PowerShell 3.0 and newer.
Another option is to create a file called TAIL.CMD with this code:
powershell -nologo "& "Get-Content -Wait %1 -Tail %2"

To do this, you can use Microsoft's more advanced command-line shell called "Windows PowerShell." It should come standard on the latest versions of Windows, but you can download it from Microsoft if you don't already have it installed.
To get the last five lines in the text file simply read the file using Get-Content, then have Select-Object pick out the last five items/lines for you:
Get-Content c:\scripts\test.txt | Select-Object -last 5
Source: Using the Get-Content Cmdlet

You can do that in some methods:
One is the type command: type filename
Another is the more command: more filename
With more you can also do that: type filename | more
The last option is using a for
for /f "usebackq delims=" %%A in (filename) do (echo.%%A)
This will go for each line and display it's content. This is an equivalent of the type command, but it's another method of reading the content.
If you are asking what to use, use the more command as it will make a pause.

If you want it to display the content of the file live, and update when the file is altered, just use this script:
#echo off
:start
cls
type myfile.txt
goto start
That will repeat forever until you close the cmd window.

There is no built in option available with Windows. To constantly monitor logs you can use this free application BareTailPro.

You can get the TAIL utility from the Windows Server 2003 Resource Kit Tools.
Here are additional details -- Tail command for Windows (CMD).

If you want to display for example all .config (or .ini) file name and file content into one doc for user reference (and by this I mean user not knowing shell command i.e. 95% of them), you can try this :
FORFILES /M *myFile.ini /C "cmd /c echo File name : #file >> %temp%\stdout.txt && type #path >> %temp%\stdout.txt && echo. >> %temp%\stdout.txt" | type %temp%\stdout.txt
Explanation :
ForFiles : loop on a directory (and child, etc) each file meeting criteria
able to return the current file name being process (#file)
able to return the full path file being process (#path)
Type : Output the file content
Ps : The last pipe command is pointing the %temp% file and output the aggregate content. If you wish to copy/paste in some documentation, just open the stdout.txt file in textpad.

You can use either more filename.[extension] or type filename.[extension]

tail -3 d:\text_file.txt
tail -1 d:\text_file.txt
I assume this was added to Windows cmd.exe at some point.

Related

Change Windows command prompt to show only current folder

Instead of showing
C:\Users\test_user\Documents\Folder\etc
show
\etc
or if possible limit it to a certain number
\Document\Folder\etc
If you check in help prompt /? there are two options that can either show the current drive or full path.
I would suggest to use new line option along with the Drive so that you will get more space to view/type the command using below combination.
prompt $P$_$G
With this you will be able to see the Path in the line above the prompt.
In short, can't see a simple way of doing it.
In order to change the prompt options you can use the prompt command. The configuration you're looking for isn't listed.
The available options can be viewed by
prompt /? in the command window.
https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/prompt.mspx?mfr=true
The following is a simple batch script which can set the prompt to include only the current folder. Note that it does not work on directory names with certain characters such as parenthesis and spaces. I named it cdd.bat.
#echo off
cd %1
for %%i in (%CD%) do set NEWDIR=%%~ni
PROMPT %NEWDIR%$G
Like others pointed out, you can use the command - prompt to set the text that is shown in cmd.
While you cannot dynamically set the path to just the parent folder, you can manually set it using:
prompt {text}
So in your case, you can set it as:
prompt etc\$G
This will result in:
etc\>
$G adds an arrow sign. You can refer the documentation for detailed explanation.
Here is a .ps1 file i use to do this for myself.
<#
FileName: promptPsShort.ps1
To set the prompt to the last folder name in the path:
> function prompt {$l=Get-Location; $p="$l".split("\")[-1]; "PS $p> "}
# works at cmd prompt, BUT NOT DIREECTLY from a .ps1 file.
RESEARCH
1. google: powershell 7 copy text into clipboard
[How to copy text from PowerShell](https://superuser.com/q/302032/236556)
[Set-Clipboard](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/?view=powershell-7)
2. google: powershell escape double quote
[Escaping in PowerShell](http://www.rlmueller.net/PowerShellEscape.htm)
3. google: powershell raw string
[About Quoting Rules](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7)
4. Usage example: powershell
PS C:\flutter_beta\flutter\examples\catalog\android\app\src\main> pwd
Path
----
C:\flutter_beta\flutter\examples\catalog\android\app\src\main
PS C:\flutter_beta\flutter\examples\catalog\android\app\src\main> promptPsShort.ps1
Paste the current Clipboard contents into the Powershell Command Line and press Enter.
PS C:\flutter_beta\flutter\examples\catalog\android\app\src\main> function prompt {$l=Get-Location; $p="$l".split("\")[-1]; "PS $p> "}
PS main>
PS main>
PS main>
#>
$shortPromptCmdStr = #'
function prompt {$l=Get-Location; $p="$l".split("\")[-1]; "PS $p> "}
'#
Set-Clipboard -Value $shortPromptCmdStr
write-host "Paste the current Clipboard contents into the Powershell Command Line and press Enter."
Love and peace,
Joe

Create an empty file on the commandline in windows (like the linux touch command)

On a windows machine I get this error
'touch' is not recognized as an internal or external command, operable program or batch file.
I was following these instructions which seem to be linux specific, but on a standard windows commandline it does not work like this:
touch index.html app.js style.css
Is there a windows equivalent of the 'touch' command from the linux / mac os / unix world ? Do I need to create these files by hand (and modify them to change the timestamp) in order to implement this sort of command? I am working with node and that doesn't seem very ... node-ish...
An easy way to replace the touch command on a windows command line like cmd would be:
type nul > your_file.txt
This will create 0 bytes in the your_file.txt file.
This would also be a good solution to use in windows batch files.
Another way of doing it is by using the echo command:
echo.> your_file.txt
echo. - will create a file with one empty line in it.
If you need to preserve the content of the file use >> instead of >
> Creates a new file
>> Preserves content of the file
Example
type nul >> your_file.txt
You can also use call command.
Calls one batch program from another without stopping the parent batch program. The call command accepts labels as the target of the call.
Example:
call >> your_file.txt
---
or even if you don't want make it hard you can Just install Windows Subsystem for Linux (WSL). Then, type.
wsl touch
or
wsl touch textfilenametoedit.txt
Quotes are not needed.
Windows does not natively include a touch command.
You can use any of the available public versions or you can use your own version. Save this code as touch.cmd and place it somewhere in your path
#echo off
setlocal enableextensions disabledelayedexpansion
(for %%a in (%*) do if exist "%%~a" (
pushd "%%~dpa" && ( copy /b "%%~nxa"+,, & popd )
) else (
type nul > "%%~fa"
)) >nul 2>&1
It will iterate over it argument list, and for each element if it exists, update the file timestamp, else, create it.
You can use this command: ECHO >> filename.txt
it will create a file with the given extension in the current folder.
UPDATE:
for an empty file use: copy NUL filename.txt
On windows Power Shell, you can use the following command:
New-Item <filename.extension>
or
New-Item <filename.extension> -type file
Note: New-Item can be replaced with its alias ni
The answer is wrong, it only works when the file does not exist. If the file exists, using the first does nothing, the second adds a line at the end of the file.
The correct answer is:
copy /b filename.ext +,,
I found it here: https://superuser.com/questions/10426/windows-equivalent-of-the-linux-command-touch/764721#764721
I'm surprised how many answers here are just wrong. Echoing nothing into a file will fill the file with something like ECHO is ON, and trying to echo $nul into a file will literally place $nul into the file. Additionally for PowerShell, echoing $null into a file won't actually make a 0kb file, but something encoded as UCS-2 LE BOM, which can get messy if you need to make sure your files don't have a byte-order mark.
After testing all the answers here and referencing some similar ones, I can guarantee these will work per console shell. Just change FileName.FileExtension to the full or relative-path of the file you want to touch; thanks to Keith Russell for the COPY NUL FILE.EXT update:
CMD w/Timestamp Updates
copy NUL FileName.FileExtension
This will create a new file named whatever you placed instead of FileName.FileExtension with a size of 0 bytes. If the file already exists it will basically copy itself in-place to update the timestamp. I'd say this is more of a workaround than 1:1 functionality with touch but I don't know of any built-in tools for CMD that can accomplish updating a file's timestamp without changing any of its other content.
CMD w/out Timestamp Updates
if not exist FileName.FileExtension copy NUL FileName.FileExtension
Powershell w/Timestamp Updates
if (!(Test-Path FileName.FileExtension -PathType Leaf)) {New-Item FileName.FileExtension -Type file} else {(ls FileName.FileExtension ).LastWriteTime = Get-Date}
Yes, it will work in-console as a one-liner; no requirement to place it in a PowerShell script file.
PowerShell w/out Timestamp Updates
if (!(Test-Path FileName.FileExtension -PathType Leaf)) {New-Item FileName.FileExtension -Type file}
Use the following command on the your command line:
fsutil file createnew filename requiredSize
The parameters info as followed:
fsutil - File system utility ( the executable you are running )
file - triggers a file action
createnew - the action to perform (create a new file)
filename - would be literally the name of the file
requiredSize - would allocate a file size in bytes in the created file
install npm on you machine
run the below command in you command prompt.
npm install touch-cli -g
now you will be able to use touch cmd.
You can replicate the functionality of touch with the following command:
$>>filename
What this does is attempts to execute a program called $, but if $ does not exist (or is not an executable that produces output) then no output is produced by it. It is essentially a hack on the functionality, however you will get the following error message:
'$' is not recognized as an internal or external command,
operable program or batch file.
If you don't want the error message then you can do one of two things:
type nul >> filename
Or:
$>>filename 2>nul
The type command tries to display the contents of nul, which does nothing but returns an EOF (end of file) when read.
2>nul sends error-output (output 2) to nul (which ignores all input when written to). Obviously the second command (with 2>nul) is made redundant by the type command since it is quicker to type. But at least you now have the option and the knowledge.
as mentioned
echo >> index.html
it can be any file, with any extension
then do
notepad index.html
this will open your file in the notepad editor
No command – neither typenor echo– is necessary to emulate Unix's/Mac OS X's 'touch' command in a Windows Powershell terminal. Simply use the following shorthand:
$null > filename
This will create an empty file named 'filename' at your current location. Use any filename extension that you might need, e.g. '.txt'.
Source: https://superuser.com/questions/502374/equivalent-of-linux-touch-to-create-an-empty-file-with-powershell (see comments)
For a very simple version of touch which would be mostly used to create a 0 byte file in the current directory, an alternative would be creating a touch.bat file and either adding it to the %Path% or copying it to the C:\Windows\System32 directory, like so:
touch.bat
#echo off
powershell New-Item %* -ItemType file
Creating a single file
C:\Users\YourName\Desktop>touch a.txt
Directory: C:\Users\YourName\Desktop
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2020-10-14 10:28 PM 0 a.txt
Creating multiple files
C:\Users\YourName\Desktop>touch "b.txt,c.txt"
Directory: C:\Users\YourName\Desktop
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2020-10-14 10:52 PM 0 b.txt
-a---- 2020-10-14 10:52 PM 0 c.txt
Also
Works both with PowerShell and the Command Prompt.
Works with existing subdirectories.
Does not create a file if it already exists:
New-Item : The file 'C:\Users\YourName\Desktop\a.txt' already exists.
For multiple files, creates only the files that do not exist.
Accepts a comma-separated list of filenames without spaces or enclosed in quotes if spaces are necessary:
C:\Users\YourName\Desktop>touch d.txt,e.txt,f.txt
C:\Users\YourName\Desktop>touch "g.txt, 'name with spaces.txt'"
You can also use copy con [filename] in a Windows command window (cmd.exe):
C:\copy con yourfile.txt [enter]
C:\CTRL + Z [enter] //hold CTRL key & press "Z" then press Enter key.
^Z
1 Files Copied.
This will create a file named yourfile.txt in the local directory.
I use cmder (a command line emulator)
It allows you to run all Linux commands inside a Windows machine.
It can be downloaded from https://cmder.net/
I really like it
From the Terminal of Visual Code Studio on Windows 10, this is what worked for me to create a new file:
type > hello.js
echo > orange.js
ni > peach.js
As Raghuveer points out in his/her answer, ni is the PowerShell alias for New-Item, so you can create files from a PowerShell prompt using ni instead of touch.
If you prefer to type touch instead of ni, you can set a touch alias to the PowerShell New-Item cmdlet.
Creating a touch command in Windows PowerShell:
From a PowerShell prompt, define the new alias.
Set-Alias -Name touch -Value New-Item
Now the touch command works almost the same as you are expecting. The only difference is that you'll need to separate your list of files with commas.
touch index.html, app.js, style.css
Note that this only sets the alias for PowerShell. If PowerShell isn't your thing, you can set up WSL or use bash for Windows.
Unfortunately the alias will be forgotten as soon as you end your PowerShell session. To make the alias permanent, you have to add it to your PowerShell user profile.
From a PowerShell prompt:
notepad $profile
Add your alias definition to your profile and save.
If you have Cygwin installed in your PC, you can simply use the supplied executable for touch (also via windows command prompt):
C:\cygwin64\bin\touch.exe <file_path>
Assuming the file exists and you just need to update the timestamp.
type test.c > test.c.bkp && type test.c.bkp > test.c && del test.c.bkp
Use rem. > file.txt (notice the dot attached to the command "rem")
this creates an empty file
Shortest possible vanilla solution is :
.>myfile.txt
You will get an error , but file is created :
If you are using VS Code, there is a command line tool code to help you open a non-exist file in VS Code.
There is something missing in all of the other answers. The Linux touch command has a -t option, which lets you set the last modified time to any arbitrary date and time, not just the current time.
This sets the modification date of filename.txt to 20 December 2012 at 30 minutes after midnight.
touch -t 201212210030 filename.txt
To get the equivalent in Windows, you need to be in PowerShell, it can't be done in Cmd.
Change the creation date/timestamp of a file named filename.txt:
(Get-Item "D:\Test\filename.txt").CreationTime=("21 December 2012 00:30:00")
Change the last write date/timestamp of a file named filename.txt:
(Get-Item "D:\Test\filename.txt").LastWriteTime=("21 December 2012 00:30:00")
Change the last accessed date/timestamp of a file named filename.txt:
(Get-Item "D:\Test\filename.txt").LastAccessTime=("21 December 2012 00:30:00")
Using PowerShell, type: ni index.html or ni style.css or ni app.js
ni <filename>.<extension>
If you have WSL with the appropriate distro like Ubuntu you can have the touch command in the CMD and not just the bash terminal. It works for me on Windows 10 & 11 Windows Terminal
Easy, example with txt file
echo $null >> filename.txt
Yes you can use Node for Touch I just use that and its working all fine in windows Cmd or gitbash
Use type instead of touch
type YOUR_FILE_NAME
However, it is limited to just a single file

How do I store the output to a file AFTER cmd execution?

I have the below code that executes and stores the output to a text file, and then display the output to console.
robocopy %TOBEZIPPED% %TEMPDIR% *.* /E > Log.txt & type Log.txt
but since I'm using the robocopy command that shows progress while it is copying, I would like it to show as it was intended and then store the output (maybe history of the command) to a text file..
How can I do it? I've tried doskey /history from a google search but can't still solve my issue.
Hope someone can help me.. Thanks in advance..
EDIT: I have searched related questions but have not found the same with what I wanted.. please note that the result of output should be displayed first normally (not echoed or typed, see robocopy command) before redirecting it to the output file.. so it's like command will display first as usual, like a command history - after execution, will then be redirected to an output file..
For Shell only:
Use tee:
tee is a command in command-line interpreters (shells) using standard streams which reads standard input and writes it to both standard output and one or more files, effectively duplicating its input.
e.g.
robocopy %TOBEZIPPED% %TEMPDIR% *.* /E | tee -a Log.txt
If you want to do it in windows you need to use PowerShell http://en.wikipedia.org/wiki/Windows_PowerShell . This will provide you tee command to be executable on windows.

Windows command line using directory and EXE file parameters

I have been trying to run an application I built and output it to a file. However, I am running into problems with the command line arguments required to do this.
This is an example of my problem using ipconfig.
The following command works:
ipconfig > output.txt
Whereas this will create the file, but not populate it with the ipconfig output:
start /D "C:\>WINDOWS\system32" ipconfig.exe > output.txt
I think it is the use of start that is causing this issue, but I'm not sure.
SOLUTION
This is the code which managed to solve the problem for me:
char path[500]; // Create character array
strcpy (path, "cd "); // Copy 'cd' into the array
strcat (path, toolLocation); // Copy the path of the tool into the array
strcat (path, " & ip.exe > output.txt"); // Append on the name of the exe and output to a file
system (path); // Run the built array
I am creating a character array and then appending to it. The vital bit here was the & being used in the system call. This is working as an and and first cd'ing to the directory before executing the .exe file.
In your command, the > is redirecting the output of start rather than the output of ipconfig. That explains why you are seeing nothing – start is simply not outputting anything.
Based on the comments to the question, you can achieve your goals with ShellExecute like this:
ShellExecute(
0,
"open",
"cmd.exe",
"/C ipconfig > output.txt",
NULL,
SW_HIDE
);
Rather than using start I think you might want to use cd to change the directory.
Try this batch file:
cd "C:\Program Files\Tools\2012"
ip.exe >output.txt
Or for use without a batch and just command line:
"C:\Program Files\Tools\2012" ip.exe >output.txt"
Although system32 is in PATH so I'm not sure why you are accessing the ipconfig exe by it's full path, but this should work.
The error is this:
start /D "C:\>WINDOWS\system32" ipconfig.exe > output.txt
should be
start /D "C:\WINDOWS\system32" ipconfig.exe > output.txt
without > in the path. Although C:\> is shown at the prompt with cmd.exe it is not part of the path name and > is actually invalid for the purpose, to my knowledge.
Additionally I would strongly suggest you use:
start /D "%SystemRoot%\system32" ipconfig.exe > output.txt
Furthermore because start creates a new console (and new stderr and stdout) you are catching the output of start not of ipconfig. So you may wanna use:
pushd "%SystemRoot%\system32" & ipconfig.exe > output.txt & popd
but that will attempt to write output.txt into %SystemRoot%\system32 and will fail on most systems unless you are admin. So give an absolute path or simply leave out the crud:
ipconfig.exe > output.txt
ipconfig.exe is always in the default system PATH variable, so it will work unless the admin has "fixed" the system in which case you can still do:
%SystemRoot%\system32\ipconfig.exe > output.txt

How to use cmd type pipe (/piping) in PowerShell?

In cmd (and bash), pipe "|" pushes output to another command in the original format of the first command's output (as string).
In PowerShell, everything that comes out the pipe is an object (even a string is a string object).
Because of that, some commands fail when run in a PowerShell command window as opposed to a Windows command window.
Example:
dir c:\windows | gzip > test.gz
When this command is run in the Windows command prompt window it works properly - directory listing of C:\windows gets compressed into test.gz file.
The same command in PowerShell fails, because PowerShell does not use cmd-style pipe and replaces it with PowerShell pipe (working with array of file system items).
Q. How do you disable the default piping behavior in PowerShell to make traditional Windows commands work identically in PowerShell?
I tried using the escape character "`" before the pipe "`|", but it didn't work. I also tried invoke-expression -command "command with | here", but it also failed.
if you want to send strings down the pipeline you can use the cmdlet "out-string"
For Example:
get-process | out-string
If you are specifically looking for a PowerShell way to zip up files, check out the PowerShell Community Extensions. there are a bunch of cmdlets to zip and unzip all kinds of files.
http://pscx.codeplex.com
If you can pipe the output of (CMD) dir into gzip, then gzip apparently knows how to parse dir output. The (string) output from the PowerShell dir command (aka Get-ChildItem) doesn't look the same, so gzip likely would not be able to parse it. But, I'd also guess that gzip would be happy to take a list of paths, so this would probably work:
dir c:\windows | select -ExpandProperty FullName | gzip > test.gz
No warrantees express or implied.
If you really need to use the old school DOS pipe system in PowerShell, it can be done by running a command in a separate, temporary DOS session:
& cmd /c "dir c:\windows | gzip > test.gz"
The /c switch tells cmd to run the command then exit. Of course, this only works if all the commands are old school DOS - you can't mix-n-match them with PowerShell commands.
While there are PowerShell alternatives to the example given in the question, there are lots of DOS programs that use the old pipe system and will not work in PowerShell. svnadmin load is one that I've the pleasure of having to deal with.
You can't. PowerShell was designed to pass objects down a pipeline, not text. There isn't a backwards-compatability mode to DOS.

Resources