Redirection and Pipes

Index

A number of Dos commands send output to the screen and/or require input from the user. Redirection is a mechanism whereby the output of a command can be fed either to some other device (eg a printer or file) or to another program or command.

There are four redirection functions:
>Redirect output
>>Append
<Redirect input
|Pipe


>

Redirects a command's output from the "standard output device" (usually the monitor) to another device (eg printer) or a file.

Syntax:

To redirect output to a device:
Command > Device

To redirect output to a file:
Command > Filename

Notes:

  1. Acceptable Device names are: CON (Monitor); PRN (LPT1 - assumed to be the printer); LPT1 - 3 (Parallel Ports - usually connected to a printer); COM 1 - 4 (Serial Ports); and NUL (an electronic void). If anything other than a recognized device is specified, it is assumed to be the name of a file.
  2. If a file already exists with the specified Filename, it is overwritten without any warnings.

Examples:

Probably the most common uses of this redirection function is to send directory listings to the printer or to save them as a file. (One of Windows Explorer's biggest weaknesses is that it does not enable either of these operations).

  1. To print out a sorted directory listing of all files in the Windows directory:
    DIR c:\windows /o/a > PRN
  2. To create a file containing the directory listing of the same directory:
    DIR c:\windows /o/a > c:\data\directories\windows.txt


>>

Appends the output from a command to the specified file.

Syntax:


Command >> Filename

Note:

If Filename does not exist, it is created. If Filename does exist, the output from the command is added to it (unlike the > function where the original contents are overwritten).

Example:

To add the directory listing of the files in the c:\windows\system directory to that created above:
DIR c:\windows\system /o/a >> c:\data\directories\windows.txt


<

Directs input to a command from a source other than the default (the default source usually being the keyboard).

Syntax:

Command < Datasource

Example:

To sort the lines in a text file (c:\data\address list.txt) on the 12th character, the SORT command is fed input from the file:
SORT /+12 < c:\data\address list.txt


|

The "pipe" redirects the output of a program or command to a second program or command.

Syntax:

Command1 | Command2

Example:

To sort a directory listing based on the time the files were last modified, the output of a directory listing is piped to the SORT filter which sorts on the 39th character of each line:
DIR c:\data\docs | SORT /+39

Note that if the output of the DIR command had been redirected to SORT /+39 using >, Dos would return an "invalid switch" error after attempting to create a file called Sort.


This page last revised:
December 9, 1999.