Windows command line pipe command

  • SS64
  • CMD
  • How-to

How-to: Redirection

command > filename
command
>&n
 
Redirect command output to a file
Redirect command output to the input of handle n
 
command >> filename
 
APPEND into a file
 
command < filename
command
<&n
 
Type a text file and pass the text to command.
Read input from handle n and write it to command.
 
commandA | commandB
 
Pipe the output from commandA into commandB
 
commandA & commandB Run commandA and then run commandB
commandA && commandB Run commandA, if it succeeds then run commandB
commandA || commandB Run commandA, if it fails then run commandB

commandA && commandB || commandC

If commandA succeeds run commandB, if commandA fails run commandC
If commandB fails, that will also trigger running commandC.

Success and failure are based on the Exit Code of the command.
In most cases the Exit Code is the same as the ErrorLevel

For clarity the syntax on this page has spaces before and after the redirection operators, in practice you may want to omit those to avoid additional space characters being added to the output. Echo Demo Text> Demofile.txt

Numeric handles:

STDIN  = 0  Keyboard input
STDOUT = 1  Text output
STDERR = 2  Error text output
UNDEFINED = 3-9 (In PowerShell 3.0+ these are defined)

When redirection is performed without specifying a numeric handle, the the default < redirection input operator is zero (0) and the default > redirection output operator is one (1). This means that ‘>‘ alone will not redirect error messages.

   command 2> filename       Redirect any error message into a file
   command 2>> filename      Append any error message into a file
  (command)2> filename       Redirect any CMD.exe error into a file
   command > file 2>&1       Redirect errors and output to one file
   command > fileA 2> fileB  Redirect output and errors to separate files

   command 2>&1 >filename    This will fail!

Redirect to NUL (hide errors)

   command 2> nul            Redirect error messages to NUL
   command >nul 2>&1         Redirect error and output to NUL
   command >filename 2> nul  Redirect output to file but suppress error
  (command)>filename 2> nul  Redirect output to file but suppress CMD.exe errors

Any long filenames must be surrounded in «double quotes».
A CMD error is an error raised by the command processor itself rather than the program/command.

Some commands, (e.g. COPY) do not place all their error mesages on the error stream, so to capture those you must redirect both STDOUT and
STDERR with command > file 2>&1

Redirection with > or 2> will overwrite any existing file.

You can also redirect to a printer with > PRN or >LPT1 or to the console with >CON

To prevent the > and < characters from causing redirection, escape with a caret: ^> or ^<

Redirection — issues with trailing numbers

Redirecting a string (or variable containing a string) will fail to work properly if there is a single numeral at the end, anything from 0 to 9.
e.g. this will fail:
Set _demo=abc 5
Echo %_demo%>>demofile.txt

One workaround for this is to add a space before the ‘>>’ but that space will end up in the output.
Moving the redirection operator to the front of the line completely avoids this issue, but is undocumented syntax.:

Set _demo=abc 5
>>demofile.txt Echo %_demo%

Create a new file

Create an empty file using the NUL device:

Type NUL >EmptyFile.txt
or
Copy NUL EmptyFile.txt
or
BREAK > EmptyFile.txt

Multiple commands on one line

In a batch file the default behaviour is to read and expand variables one line at a time, if you use & to run multiple commands on a single line, then any variable changes will not be visible until execution moves to the next line. For example:

 SET /P _cost=»Enter the price: » & ECHO %_cost%

This behaviour can be changed using SETLOCAL EnableDelayedExpansion

Redirect multiple lines

Redirect multiple lines by bracketing a set of commands:

(
  Echo sample text1
  Echo sample text2
) > c:\logfile.txt

Unicode

The CMD Shell can redirect ASCII/ANSI (the default) or Unicode (UCS-2 le) but not UTF-8.
This can be selected by launching CMD /A or CMD /U

In Windows 7 and earlier versions of Windows, the redirection operator ‘>’ would strip many Extended ASCII /Unicode characters from the output.
Windows 10 no longer does this.

Pipes and CMD.exe

You can redirect and execute a batch file into CMD.exe with:

CMD < sample.cmd

Surprisingly this will work with any file extension (.txt .xls etc) if the file contains text then CMD will attempt to execute it. No sanity checking is performed.

When a command is piped into any external command/utility ( command | command ) this will instantiate a new CMD.exe instance.
e.g.
TYPE test.txt | FIND «Smith»

Is in effect running:

TYPE test.txt | cmd.exe /S /D /C FIND «Smith»

This has a couple of side effects:
If the items being piped (the left hand side of the pipe) include any caret escape characters ^ they will need to be doubled up so that they survive into the new CMD shell.
Any newline (CR/LF) characters in the first command will be turned into & operators. (see StackOverflow)

On modern hardware, starting a new CMD shell has no noticable effect on performance.

For example, this syntax works, but would fail if the second or subsequent (piped) lines were indented with a space:
@Echo Off
Echo abc def |^
Find «abc» |^
Find «def»> outfile.txt

Multi-line single commands with lots of parameters, can be indented as in this example:

Echo abc def ^
  ghi jkl ^

  mno pqr

Redirection anywhere on the line

Although the redirection operator traditionally appears at the end of a command line, there is no requirement that it do so.
All of these commands are equivalent:

Echo A B>C
Echo A>C B
Echo>C A B
>C Echo A B

All of them Echo «A B» to the file «C».

If the command involves a pipe such as DIR /b | SORT /r then you will still want to put the redirection at the end so that it captures the result of the SORT, but there are some advantages to putting the redirection at the start of the line.

Code like this:

Set _message=Meet at 2
Echo %_message%>schedule.txt

Will inadvertently interpret the “2” as part of the redirection operator.

One solution is to insert a space:

Echo %_message% >schedule.txt 

This assumes that the space won’t cause a problem. If you’re in a case where that space will indeed cause a problem, you can use the trick above to move the redirection operator to a location where it won’t cause any trouble:

>schedule.txt Echo %_message%  

Example via Raymond Chen

The idea of redirection anywhere in the line was first introduced in version 2 of sh, written by Ken Thompson in 1972.

Exit Codes

If the filename or command is not found then redirection will set an Exit Code of 1

When redirecting the output of DIR to a file, you may notice that the output file (if in the same folder) will be listed with a size of 0 bytes. The command interpreter first creates the empty destination file, then runs the DIR command and finally saves the redirected text into the file.

The maximum number of consecutive pipes is 2042

Examples

   DIR >MyFileListing.txt
   
   DIR /o:n >"Another list of Files.txt"

   DIR C:\ >List_of_C.txt 2>errorlog.txt

   DIR C:\ >List_of_C.txt & DIR D:\ >List_of_D.txt

   ECHO y| DEL *.txt

   ECHO Some text ^<html tag^> more text

   COPY nul empty.txt

   MEM /C >>MemLog.txt

   Date /T >>MemLog.txt

   SORT < MyTextFile.txt

   SET _output=%_missing% 2>nul
   
   FIND /i "Jones" < names.txt >logfile.txt

   (TYPE logfile.txt >> newfile.txt) 2>nul

“Stupidity, outrage, vanity, cruelty, iniquity, bad faith, falsehood,
we fail to see the whole array when it is facing in the same direction as we” ~ Jean Rostand (French Historian)

Related commands

CON — Console device.
conIN$
and conOUT$ behave like stdin and stdout, or 0 and 1 streams but only with internal commands.
SORT — Sort input.
CMD Syntax
TYPE — Display the contents of one or more text files.
Command Redirection — Microsoft Help page (archived)
Successive redirections explained (1>&3 ) — Stack Overflow.
Equivalent PowerShell: Redirection — Spooling output to a file, piping input.
Equivalent bash command (Linux): Redirection — Spooling output to a file, piping input.


Copyright © 1999-2025 SS64.com
Some rights reserved

Windows Command line: pipe example

Self-tutoring about computer science: the tutor mentions a key element of command line thinking.

At the command line (Windows or Li|U|nix), a pipe is often shown as | and sends the first command’s output as input to the next command.

Let’s imagine, for instance, at the Windows command prompt, you’ve a long file and want to find the string “hello” in it. At the command line you could type

type longfile.txt | find /N “hello”

The type command will output the file’s contents to the pipe; find /N will receive them from the pipe as input, then display, with line numbers, those lines that contain “hello”.

ss64.com

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

  1. What does pipe do in CMD?
  2. What is the CMD symbol?
  3. What does pipe () return?
  4. Does pipe work in Windows?
  5. How does pipe work in C?
  6. How do I redirect an echo to a file?
  7. How do I open a text file in CMD?
  8. How do you use % in cmd?
  9. What does & mean in cmd?
  10. What is a Windows named pipe?
  11. What is CS pipe?
  12. What is pipe in IPC?
  13. How does pipe () work?

What does pipe do in CMD?

Pipe shell command

The | command is called a pipe. It is used to pipe, or transfer, the standard output from the command on its left into the standard input of the command on its right.

What is the CMD symbol?

The most commonly used symbols are the two redirection symbols «>» and «>>» and the so-called pipe, «¦» . (Just to make sure there is no confusion, the «pipe» is the symbol above the back slash on most keyboards.

What does pipe () return?

If pipe is empty and we call read system call then Reads on the pipe will return EOF (return value 0) if no process has the write end open.

Does pipe work in Windows?

What is a Pipe? Like most IPC mechanisms, pipes help facilitate communication between two applications and or processes using shared memory . This shared memory is treated as a file object in the Windows operating system.

How does pipe work in C?

A pipe is a system call that creates a unidirectional communication link between two file descriptors. The pipe system call is called with a pointer to an array of two integers. Upon return, the first element of the array contains the file descriptor that corresponds to the output of the pipe (stuff to be read).

How do I redirect an echo to a file?

$ echo “Hello” > hello. txt The > command redirects the standard output to a file. Here, “Hello” is entered as the standard input, and is then redirected to the file **… $ cat deserts.

How do I open a text file in CMD?

Don’t put quotes around the name of the file that you are trying to open; start «myfile. txt» opens a new command prompt with the title myfile. txt , while start myfile. txt opens myfile.

How do you use % in cmd?

Use a single percent sign ( % ) to carry out the for command at the command prompt. Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c.

What does & mean in cmd?

The & symbol instructs commands to run in a background process and immediately returns to the command line for additional commands.

What is a Windows named pipe?

A named pipe is a named, one-way or duplex pipe for communication between the pipe server and one or more pipe clients. All instances of a named pipe share the same pipe name, but each instance has its own buffers and handles, and provides a separate conduit for client/server communication.

What is CS pipe?

Carbon steel pipe is used as the base pipe of bimetallic combination tubing, which has an internal liner made of stainless steel, titanium alloy steel, copper or aluminum, and so on.

What is pipe in IPC?

Also see named pipe (or FIFO). In computer programming, especially in UNIX operating systems, a pipe is a technique for passing information from one program process to another. Unlike other forms of interprocess communication (IPC), a pipe is one-way communication only.

How does pipe () work?

pipe() is a system call that facilitates inter-process communication. It opens a pipe, which is an area of main memory that is treated as a «virtual file». The pipe can be used by the creating process, as well as all its child processes, for reading and writing.

Windows 7 / Getting Started


Normally, any output from a console program appears in the Command Prompt window,
but you can redirect it into a file using the > character. For example, the command

tasklist >tasks.txt

generates the same listing as the previous example but stores it in a file named
tasks.txt. Command-line programs send their output to what is called the standard
output stream. By default, anything the program sends to the standard output is printed
in the Command Prompt window. Figure below shows how this looks. The first tasklist command in the figure sends its output to the Command Prompt window.
The second tasklist command has its output redirected into a file.

Some programs read input through a standard input stream. By default, this is connected
to your keyboard, and whatever you type is read by the program. For example,
the sort command reads lines of text from the standard input, sorts them alphabetically,
and writes the results to the standard output. If you type the following lines at the command prompt,

sort
c
b
a
Ctrl+Z

sort spits out the lines in order: a, b, c. (Note that Ctrl+Z on a line by itself indicates
the end of input.) You can redirect the standard input with the < character. For example, the command

sort <somefile.txt

tells sort to read input from the file somefile.txt.You can use both input and output
redirection at the same time.The command

sort <somefile.txt >sortedfile.txt

rearranges the contents of somefile.txt and creates a new file named

sortedfile.txt.

You can also specify that the output isn’t to replace an existing file but rather should
simply be stuck onto the end (that is, appended ) with the characters >>, as in this example:

dir /b c:\ >listing.txt
dir /b d:\ >>listing.txt

The first command creates the file listing.txt, and the second appends its output
onto the end of listing.txt. (If the file listing.txt doesn’t already exist, don’t
worry: >> creates it.)

Finally, you can hook the output of one program directly to the input of another by
using the vertical bar symbol (|), usually found above the backslash (\) on a keyboard.
For example, the find command reads lines from the input and passes only lines containing
a designated string.The command

tasklist | find "winword"

has tasklist send its list of all programs through find which types out only the line
or lines containing «winword.» Finally,

tasklist | find "winword" >tasks.txt

connects tasklist to find, and find to a file.

Input and output redirection let you connect programs and files as if you are making
plumbing connections.The | symbol is often called a pipe for this reason, and programs
such as find are often called filters.

Note One handy filter to know about is more, a program that passes whatever it’s given as input to
its output. What makes more useful is that it pauses after printing a screen full of text. more lets
you view long listings that would otherwise scroll off the screen too quickly to read. For example, the command

tasklist | more

helps you see the entire list of programs. When you see the prompt — More — at the bottom of the
screen, press the spacebar to view the next screen full.

The standard error is another output stream available to console programs. By default, if
a program writes information to the standard error stream, the text appears in the
Command Prompt window. Programs usually use this to display important error messages
that they want you to see, even if the standard output is redirected to a file or
pipe.You can redirect standard error too, though, if you want to capture the error messages in a file.

If you’ve worked with DOS, Linux, or Unix, this is probably already familiar to you.
However, there are several input redirection variations you might not be familiar with.
Table below lists all the redirection instructions that CMD recognizes.

Input and Output Redirection

Redirection Option Action
<file Reads standard input from file.
>file Writes standard output to file.
>>file Appends standard output to file.
1>file Writes standard output to file.*
1>>file Appends standard output to file.
2>file Writes standard error to file.
2>>file Appends standard error to file.
2>&1 Directs standard error through the same stream as standard
output. Both can then be redirected to a file or piped to another program.
nextcommand Sends output to the input of nextcommand.

* The number 1 refers to the standard output stream and the number 2 to the standard error stream.

Two special forms of output redirection are output to the NUL device and output to a
printer.Windows recognizes the special filename nul in any folder on any drive and
treats it as a «black hole» file. If you issue a command and redirect its output to nul,
the output is discarded.This type of direction is useful in batch files when you want a
command to do something, but don’t want or need the user to see any error messages
it might print. For example,

net use f: /del >nul 2>nul

runs the net use command and makes sure that no output appears to the user.

Special filenames LPT1, LPT2, and so on, represent your default printer and your local
printer connected to ports LPT1, LPT2, and so on.You can direct the output of a
command to the printer using redirection to these names.You can also direct output
to network-connected printers by mapping these devices to network printers using
the net use command. Special name PRN is the same as LPT1.

In practical day-to-day use, standard output redirection lets you capture the output
of a console program into a file, where you can edit or incorporate it into your
documents. Standard error redirection is handy when you need to gather hardcopy
evidence from a program that is printing error messages. Input redirection is used most
often in a batch file setting, where you want to have a command run automatically
from input prepared ahead of time.

Here are some examples:

cmd /? | more

This has the CMD command-line shell print its built-in help information, and it
passes the text through more so it can be read a page at a time.

cmd /? > cmd.info
notepad cmd.info

This has CMD print its help information again, but this time, the text is stored in a
file, and you view the file with Notepad. (Window-based programs can be useful on occasion.)

tasklist | sort /+60 | more

This has tasklist list all running programs, and it pipes the listing through sort,
which sorts the lines starting with column 60.This produces a listing ordered by the
amount of memory used by each running program.The sorted output is piped
through more so it can be viewed a page at a time.

date /f >ping.txt
ping www.companyabc.com 2>&1 >>ping.txt

This checks whether the site www.mycompany.com can be reached through the
Internet.The results, including any errors, are stored in a file named ping.txt.You
could then view this file or analyze it with a program.

Most of you are familiar with pipe grep command in Linux. Here I am explaining the equivalent command in Windows command line.

Windows has two different command prompts. One is called the CMD and the other one is PowerShell.

PowerShell is more powerful and user friendly compared to the raw shell in windows. Most of the commands in CMD works in PowerShell, but the commands in PowerShell might not work in CMD.

What is grep command in Linux ?

grep is a command for performing filter and search operation in a file or a folder or in the output of another command.

The syntax of grep command is given below.

grep [options] pattern [files]
Options Description
-c : This prints only a count of the lines that match a pattern
-h : Display the matched lines, but do not display the filenames.
-i : Ignores, case for matching
-l : Displays list of a filenames only.
-n : Display the matched lines and their line numbers.
-v : This prints out all the lines that do not matches the pattern
-e exp : Specifies expression with this option. Can use multiple times.
-f file : Takes patterns from file, one per line.
-E : Treats pattern as an extended regular expression (ERE)
-w : Match whole word
-o : Print only the matched parts of a matching line,
with each such part on a separate output line.
-A n : Prints searched line and n lines after the result.
-B n : Prints searched line and n line before the result.
-C n : Prints searched line and n lines after before the result.

Sample usages are given below.

In the below example, the grep command filters and searches for the string “Flask” in the output of the command pip freeze

pip freeze | grep "Flask"

In the below example, the grep command searches for the string Amal in the file userlist.txt. The option -i performs case insensitive search inside the file.

grep -i "Amal" userlist.txt

grep command equivalent in Windows CMD

findstr is the command equivalent to grep.

Example is given below. In the below examples, the findstr will do an exact match

pip freeze | findstr "Flask"
netstat -an | findstr "80"

To search a string within a file, use findstr in the following way

findstr <search-string> <filename>

Example

findstr Amal userlist.txt

More details of findstr command can be found in this official documentation.

grep command equivalent in Windows PowerShell

findstr command works in powershell. We have another command in powershell which is Select-String

An example usage is given below.

netstat -an | Select-String 80

For searching a string in the contents of a file, use the below syntax

Select-String <string-to-search> <file-name>

Example

Select-String Amal userlist.txt

I hope this explanation is clear. Feel free to comment if you have any questions or suggestions.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как ускорить ноутбук на windows 10 через биос
  • Как проверить лицензию ключа windows
  • Как изменить тему рабочего стола в windows 11
  • Как сделать чтобы windows 7 загружался с флешки
  • Windows 11 как переместить панель пуск вверх