Loading

T6 Linux and Bash · Lesson 4

Redirection and pipes

Sending a command's output into a file and its errors somewhere else, joining commands with pipes so that text flows from each to the next, and the small tools that make pipes useful: grep to find lines, sort and uniq to order and count them, cut, tr and sed to change them, and xargs to turn them into arguments.

  • send output and errors into files, or throw them away, and feed a file in
  • join commands with pipes, and save a copy midway with tee
  • find lines with grep, using simple regular expressions
  • sort lines and count how often each one appears
  • cut out columns, swap characters with tr, and change text with sed
  • turn lines of text into arguments with xargs
About 55 minutesChecked against GNU Bash on the laptop (the kit compares every shell block with it, in a sandbox) 5.3.9 (2026-11-06); GNU coreutils on the laptop (installed beside Ubuntu 26.04's default uutils; the kit's sandbox uses GNU's) 9.7 (2026-11-06)Play this lesson's games

The back cover

One small command answers a small question. Join a few, so that the text from each flows into the next, and they answer big ones. Which pump fails most often in a log of thousands of lines? One line of joined commands can tell.

These pages show where a command's output and errors go, and how to send each into a file or throw it away. They show pipes, which join commands. They also show the small tools that make pipes useful: grep, sort and uniq, cut, tr and sed, and xargs.

Before you start

The story: A million lines

Every pump in the Underway writes a line in the station log each time it fails, and the log has grown past a million lines. The warden wants to know which pump fails most. Corin has started reading it from the top with a ruler and a tally sheet. He has reached Tuesday.

It is a long way to Sunday, and the pumps do not stop failing while he reads.

Warden Rao takes away the ruler. "No machine down here does two jobs," she says. "One sorts. One counts. One finds. Run a pipe from each to the next, and let the log flow through."

Each command you have met does one small job. This lesson shows the idea that makes the shell powerful: joining small commands, so that the output of one becomes the input of the next. With it, five tiny tools can answer a question about a million lines in a second.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
Commands print text.cat notes.txtThat text can go somewhere else.
Errors look different.ls: cannot access ...They travel on a separate stream.
The exit status.echo $?grep reports found or not found.
Joining with && and ||.false || echo noWith grep -q.
head and tail.head -n 3 fileCommon steps in a pipe.
Counting lines.wc -l fileCounting what flows in.
Quotes.'*.log'Patterns for grep need them too.
find's list.find . -name '*.tmp'It can feed another command.
echo into a file.echo hi > a.txtNow explained in full.
The | in find ... | sort.Used, not yet explainedNow you learn what it does.

By the end of this lesson you will be able to:

  • send output and errors into files, or throw them away, and feed a file in;
  • join commands with pipes, and save a copy midway with tee;
  • find lines with grep, using simple regular expressions;
  • sort lines and count how often each one appears;
  • cut out columns, swap characters with tr, and change text with sed;
  • turn lines of text into arguments with xargs.

How to follow this lesson

Most blocks start in a folder that holds one small station log, shown at the top of the next section. Build each pipe one step at a time: run the first command, look at what it prints, then add the next. Every pipe in this lesson was built that way.

In one line

Small commands, joined so that each one's output flows into the next, can answer big questions; this lesson teaches the joints and the tools.

Where output goes

At a glance

Think of a pump with two pipes leaving it: the main outlet, and an overflow drain for when something goes wrong. A command has two such outlets, and one inlet.

Results go to standard output and errors to standard error, and both reach your screen unless you say otherwise. The sign > sends output into a file, emptying it first, and >> adds to the end. 2> sends the errors elsewhere, /dev/null throws away whatever reaches it, and < feeds a file into a command.

Take a guess: Did errors always have an outlet of their own, apart from the results?

Think of a pump with two pipes leaving it: the main outlet, where the water goes, and an overflow drain, for when something goes wrong. A command has two such outlets as well, and one inlet. Unless you say otherwise, both outlets lead to your terminal, which is why you see results and errors mixed together.

Here is the log that most blocks in this lesson start with. Each line is a time, a pump, and either OK or FAIL with a reason:

In a folder with notes.txt and station.log, the log shown at the top of this lesson

cat station.log
08:00 pump-3 OK
08:05 pump-7 FAIL low pressure
08:10 pump-2 OK
08:15 pump-7 FAIL low pressure
08:20 pump-3 FAIL blocked valve
08:25 pump-7 OK
08:30 pump-1 FAIL low pressure
08:35 pump-7 FAIL blocked valve
08:40 pump-2 OK
08:45 pump-3 FAIL low pressure
Standard output

The stream where a command writes its normal results. Unless you send it elsewhere, it goes to the terminal.

> sends output into a file

The sign > sends standard output into a file. The file is made if it does not exist, and emptied first if it does. To add to the end of a file instead, use >>:

echo hello > greeting.txt
cat greeting.txt
echo one > list.txt
echo two > list.txt
cat list.txt
echo three >> list.txt
cat list.txt
hello
two
two
three

The second > threw away one and wrote two. The >> kept two and added three below it. One sign replaces, two signs add: remember it as more arrows, more kept.

Errors travel separately

Standard error

A second output stream, kept for error messages, so that errors still reach your screen when the results go into a file.

Watch what happens when a command has both kinds of news to give. Only the results go into the file; the error appears on the screen:

In a folder with notes.txt and station.log, the log shown at the top of this lesson

ls notes.txt nothing.txt > found.txt
cat found.txt
ls: cannot access 'nothing.txt': No such file or directory
notes.txt

The shell numbers the streams. 0 is standard input, 1 is standard output, and 2 is standard error. So 2> sends the errors into a file:

In a folder with notes.txt and station.log, the log shown at the top of this lesson

ls notes.txt nothing.txt 2> errors.txt
cat errors.txt
notes.txt
ls: cannot access 'nothing.txt': No such file or directory

To catch both streams in one file, write 2>&1 after the first redirection. It means: send stream 2 wherever stream 1 is going now. Bash also has a short form, &>, which does the same:

In a folder with notes.txt and station.log, the log shown at the top of this lesson

ls notes.txt nothing.txt > all.txt 2>&1
cat all.txt
ls notes.txt nothing.txt &> both.txt
cat both.txt
ls: cannot access 'nothing.txt': No such file or directory
notes.txt
ls: cannot access 'nothing.txt': No such file or directory
notes.txt

/dev/null throws output away

You met /dev/null in the file system lesson. Anything written to it disappears, so it is where you send output you do not want. The exit status still tells the truth:

In a folder with notes.txt and station.log, the log shown at the top of this lesson

ls notes.txt nothing.txt 2> /dev/null
echo $?
notes.txt
2

< feeds a file in

The sign < points the other way: it feeds a file into a command's standard input. A command that reads its input this way never learns the file's name, so wc prints only the count:

In a folder with notes.txt and station.log, the log shown at the top of this lesson

wc -l < notes.txt
wc -l notes.txt
3
3 notes.txt
WrittenIt doesRead it as
> fileoutput into the file, replacing what was thereinto
>> fileoutput added to the end of the fileonto the end of
2> fileerrors into the fileerrors into
> file 2>&1output and errors into one fileboth into
&> filethe same, in bash's short formboth into
2> /dev/nullerrors thrown awayhide the errors
< filethe file fed in as inputfrom

Worked example 1

Warden Rao wants the morning's failures saved in a file named fails.txt, with a line at the end saying who checked them. The log of a second station, east.log, was also asked for, but it is missing; its error must be kept apart, in errors.txt.

What we have: station.log, a missing east.log, and the three redirections

What we need: fails.txt with the failures and a signature, and errors.txt with the error

The plan: grep FAIL keeps the lines that contain FAIL (the grep section explains it); > sends them to fails.txt and 2> the error to errors.txt; then >> adds the signature

In a folder with notes.txt and station.log, the log shown at the top of this lesson

grep FAIL station.log east.log > fails.txt 2> errors.txt
echo "checked by Asha" >> fails.txt
wc -l fails.txt
cat errors.txt
7 fails.txt
grep: east.log: No such file or directory
  1. Nothing appeared on the screen while grep ran: its results went to one file and its error to the other. fails.txt holds the 6 failures and the signature, so 7 lines.

fails.txt holds 7 lines, and errors.txt holds the one error.

Check: 6 failures plus 1 signature is 7, and the error names the missing file.

A path that fails: writing the signature with > instead of >>. That would empty fails.txt first, and leave only the signature: the failures would be lost.

When you are stuck: output or errors do not go where you expected

An error still on the screen: it travels on stream 2. Add 2> file, or 2>&1 to join it with the output.

A file lost its old contents: > empties it first. Use >> to add.

A file is empty: the command may have printed only errors. Run it without the redirection to see.

Not sure what a command printed where? Run it with nothing redirected first.

Your turn

echo a > f.txt
echo b >> f.txt
echo c > f.txt
cat f.txt
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
c
  1. The first line writes a.
  2. The second adds b.
  3. The third, with one >, empties the file and writes c.

It prints c.

What does 2> send into a file, and what does > send?Tap to reveal
  1. Stream 2 is standard error.
  2. > alone means stream 1, standard output.

2> sends errors; > sends the normal output.

How do you run a command and keep none of its error messages?Tap to reveal
  1. /dev/null throws away whatever is written to it.

Add 2> /dev/null.

Did you know?

Errors once shared the main outlet

Standard error was not there at the start. The 1974 paper on Unix says that programs began with two open files, and those that wrote diagnostic information ordinarily used file 1, standard output. Doug McIlroy recalls that this became intolerable once output was sent into pipes. People put up with it through the Sixth Edition, and then Dennis Ritchie introduced the standard error file.

Why it fits here: It answers this topic's question: errors first went to standard output, until pipes made a second outlet necessary.

Sources: Dennis M. Ritchie and Ken Thompson: The UNIX Time-Sharing System; M. Douglas McIlroy: A Research UNIX Reader

A lock on the arrow

The shell can stop > from emptying a file by mistake. The bash manual says that once the noclobber option is turned on, with set -o noclobber or set -C, a redirection with > fails if the file already exists as a regular file. When you do mean to replace it, the operator >| goes ahead anyway. The option stays off until you turn it on.

Why it fits here: It adds a guard to this topic's >, which empties a file without asking: with noclobber on, bash refuses.

Source: GNU Bash manual

In one line

A command writes results to standard output and errors to standard error, and reads standard input. Use > to send output into a file, >> to add to one, 2> for errors, 2>&1 or &> for both, /dev/null to throw away, and < to feed a file in.

Pipes: from each to the next

At a glance

Saving output in a file and reading it with the next command works, but it leaves files lying about. A pipe joins two commands directly, like a real pipe from one machine's outlet to the next machine's inlet.

The sign | sends the standard output of one command into the standard input of the next. Both commands run at once, and no file sits in between. Errors skip the pipe and still reach the screen. The command tee keeps a copy of what flows past, and a pipe's exit status is its last command's.

Take a guess: Who first asked for programs to be joined like a garden hose?

Saving output in a file and then reading the file with the next command works, but it leaves files lying about. A pipe joins the two commands directly. Picture a real pipe from the outlet of one machine to the inlet of the next.

Pipe

The sign |, which connects the standard output of one command to the standard input of the next. Both commands run at once, and the text flows from one to the other with no file in between.

The | is the bar on your keyboard, usually above the Enter key with Shift. The command seq 1 10 prints the numbers 1 to 10, one a line. Pipe them into tail, and only the last three come out. Pipe them through head and then tail, and you get exactly the fifth line:

seq 1 10 | tail -n 3
seq 1 10 | head -n 5 | tail -n 1
8
9
10
5

Read the second line from left to right: make ten numbers, keep the first five, keep the last of those. That head and tail pair works on any text, so it picks out line 5 of anything.

A pipe can follow any command that prints. Here grep keeps the failure lines, and wc counts them. The grep section explains grep:

In a folder with notes.txt and station.log, the log shown at the top of this lesson

grep FAIL station.log | wc -l
6

What goes down the pipe, and what does not

Only standard output goes down a pipe. Errors still go to your screen, so the next command never sees them:

ls nothing.txt | wc -l
ls: cannot access 'nothing.txt': No such file or directory
0

The error reached the screen, and wc counted 0 lines, because nothing came down the pipe. If you do want errors to flow on, join them to the output first, with 2>&1 before the |:

ls nothing.txt 2>&1 | wc -l
1

tee: a copy on the way

Sometimes you want to keep what flows past a point and still pass it on, like a T-shaped joint in a water pipe. The command tee does exactly that: it writes its input into a file and also to its output:

In a folder with notes.txt and station.log, the log shown at the top of this lesson

grep FAIL station.log | tee fails.txt | wc -l
head -n 2 fails.txt
6
08:05 pump-7 FAIL low pressure
08:15 pump-7 FAIL low pressure

A pipe's exit status

A whole pipe gives one exit status, and it is the status of the last command. Here grep finds nothing and fails, but wc then counts 0 lines and succeeds, so the pipe reports success:

In a folder with notes.txt and station.log, the log shown at the top of this lesson

grep NOTHING station.log | wc -l
echo $?
0
0

That is usually what you want at the keyboard. In a script it can hide a failure, and the scripts lesson shows the setting that changes it, set -o pipefail.

You wantPipe into
only the first lines| head
only the last lines| tail
to count the lines| wc -l
them in order| sort
to read it one screen at a time| less
a copy kept on the way| tee file

Worked example 2

Warden Rao wants two quick answers: the last failure of the morning, and the fifth entry in the log. Each must be one line, and no file may be left behind.

What we have: station.log, and the commands grep, head and tail

What we need: two lines, one for each answer

The plan: for the last failure, keep the failures and then the last of them; for the fifth entry, keep five lines and then the last of those

In a folder with notes.txt and station.log, the log shown at the top of this lesson

grep FAIL station.log | tail -n 1
head -n 5 station.log | tail -n 1
08:45 pump-3 FAIL low pressure
08:20 pump-3 FAIL blocked valve
  1. Each pipe passes its text straight on, so no file was written.

The last failure was pump-3 at 08:45, and the fifth entry is pump-3's blocked valve at 08:20.

Check: the log at the top of the section has the same lines last and fifth.

A path that fails: grep FAIL station.log | head -n 1. That keeps the first failure, at 08:05, not the last one.

When you are stuck: a pipe gives nothing, or not what you expected

Run the first command alone, then add one | at a time, and look at what each step gives.

Add | head to a step to look at a few lines of a long stream.

An error appeared but was not counted: errors skip the pipe. Use 2>&1 before the | if they should flow on.

The line seems to hang: a command with no file name may be waiting for you to type. Press Ctrl+C.

Your turn

seq 1 5 | tail -n 2 | head -n 1
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
4
  1. seq makes 1 to 5.
  2. tail -n 2 keeps 4 and 5.
  3. head -n 1 keeps 4.

It prints 4.

How do you see only the first 3 lines of what ls -l prints?Tap to reveal
  1. Pipe it into head.

ls -l | head -n 3.

Why does ls nothing.txt | wc -l print an error and then 0?Tap to reveal
  1. The error goes to standard error, straight to the screen.
  2. Nothing went to standard output, so wc counted nothing.

Because errors do not go down a pipe, and no output did.

Did you know?

A garden hose in 1964

Pipes were asked for long before Unix. In a Bell Labs memo of 1964, Doug McIlroy wrote that there should be ways of connecting programs like a garden hose, screwing in another segment when data needs another kind of work. Dennis Ritchie says pipes reached Unix in 1972 at McIlroy's suggestion, or perhaps insistence. McIlroy's own history adds that Ken Thompson built them in one feverish night.

Why it fits here: It answers this topic's question: Doug McIlroy wished for programs joined like a garden hose in 1964, and pipes came in 1972.

Sources: Dennis M. Ritchie: Prophetic Petroglyphs; Dennis M. Ritchie: The Evolution of the Unix Time-sharing System; M. Douglas McIlroy: A Research UNIX Reader

A pipe holds 64 KiB

A pipe is a small store, not an endless tube. The Linux manual says that since Linux 2.6.11 a pipe holds 65,536 bytes on a system with 4096-byte pages, and a command that writes to a full pipe waits until the next one reads. When the reader closes its end, as head does after its lines, the writer gets the signal SIGPIPE and stops. That is why yes | head -n 3 ends at once, though yes prints forever until it is killed.

Why it fits here: It shows how this topic's two commands run at once: the pipe is a small store, and each side waits for the other.

Sources: Linux man-pages: pipe(7); Linux man-pages: signal(7); GNU Coreutils manual: yes invocation

In one line

A pipe, |, sends one command's output straight into the next command's input, with no file in between. Errors skip the pipe. The command tee keeps a copy on the way, and a pipe's exit status is its last command's.

Finding lines: grep

At a glance

The command grep reads lines and keeps only the ones that match a pattern. It is the sieve of the shell, and people use it every day.

Its options change what it keeps or reports: -c counts, -v keeps the lines that do not match, -n numbers them, -i ignores capitals, and -w matches whole words. Its patterns are regular expressions, where ^ is the start of a line, $ the end, a dot any one character, and a star repeats what comes before it. With -r it searches a whole folder.

Take a guess: Does grep read every single byte of a file to find a word?

The command grep reads lines and keeps only the ones that match a pattern. It is the sieve of the shell, and you will use it every day. Its odd name comes from an old Unix editor, where g/re/p meant: go through every line, find the regular expression, and print the line.

In a folder with notes.txt and station.log, the log shown at the top of this lesson

grep FAIL station.log
08:05 pump-7 FAIL low pressure
08:15 pump-7 FAIL low pressure
08:20 pump-3 FAIL blocked valve
08:30 pump-1 FAIL low pressure
08:35 pump-7 FAIL blocked valve
08:45 pump-3 FAIL low pressure

grep looks for the pattern anywhere in each line, and capitals count. A handful of options change what it keeps or what it reports:

OptionIt doesA way to remember
-cprints how many lines match, not the linesc for count
-vkeeps the lines that do not matchv for inVert
-nputs each line's number in frontn for number
-iignores capitalsi for ignore case
-wmatches whole words onlyw for word
-xmatches whole lines onlyx for exact
-oprints only the matching parto for only
-rsearches every file in a folder, all the way downr for recursive

In a folder with notes.txt and station.log, the log shown at the top of this lesson

grep -c FAIL station.log
grep -v FAIL station.log
grep -n pump-7 station.log
grep -i fail station.log | wc -l
6
08:00 pump-3 OK
08:10 pump-2 OK
08:25 pump-7 OK
08:40 pump-2 OK
2:08:05 pump-7 FAIL low pressure
4:08:15 pump-7 FAIL low pressure
6:08:25 pump-7 OK
8:08:35 pump-7 FAIL blocked valve
6

The difference between a word and a part of a word matters. Without -w, cat is found inside catalog and bobcat as well:

printf writes three words, one a line, into words.txt

printf 'cat\ncatalog\nbobcat\n' > words.txt
grep cat words.txt
grep -w cat words.txt
cat
catalog
bobcat
cat

Patterns: regular expressions

Regular expression

A pattern that describes a set of texts, written with characters that have special meanings. grep, sed and many programming languages understand them. It is a different language from the shell's globs.

The most important difference from globs: in a regular expression, . means any one character, and * means the thing before it, repeated any number of times, even none. These are the ones to learn first:

CharacterMeansExampleMatches
^the start of the line'^08:4'lines that start 08:4
$the end of the line'valve$'lines that end in valve
.any one character'pump-.'pump- and one more character
[0-9]one character from the set'pump-[17]'pump-1 or pump-7
*the thing before it, any number of times'[0-9]*'a run of digits, even none

In a folder with notes.txt and station.log, the log shown at the top of this lesson

grep '^08:4' station.log
grep 'valve$' station.log
grep -o 'pump-[0-9]*' station.log | sort -u
08:40 pump-2 OK
08:45 pump-3 FAIL low pressure
08:20 pump-3 FAIL blocked valve
08:35 pump-7 FAIL blocked valve
pump-1
pump-2
pump-3
pump-7

The last line printed each pump's name once: -o kept only the matching part, and sort -u, from the next section, sorted the names and kept one of each.

With -E, grep understands a few more signs, which is why it is called extended: + for one or more, ? for maybe, | for or, and round brackets to group:

In a folder with notes.txt and station.log, the log shown at the top of this lesson

grep -E 'pump-(1|2) ' station.log
08:10 pump-2 OK
08:30 pump-1 FAIL low pressure
08:40 pump-2 OK

Quote every pattern

Put grep's pattern in single quotes. Characters such as *, $, [ and | mean something to the shell too, and without quotes the shell changes them before grep sees them.

Found or not found

The exit status of grep is 0 when it finds a line, 1 when it finds none, and 2 when something went wrong, such as a missing file. The option -q keeps grep quiet, so that only the status speaks. That makes it a test for && and ||:

In a folder with notes.txt and station.log, the log shown at the top of this lesson

grep -q FAIL station.log && echo "something failed"
grep -q BROKEN station.log || echo "nothing broken"
grep FAIL nothing.log
echo $?
something failed
nothing broken
grep: nothing.log: No such file or directory
2

Searching a whole folder

With -r, grep searches every file below a folder, and puts the file's name before each match. With -l it lists only the names of the files that match. The order follows the disk, so these blocks sort it:

In a folder with a logs folder of three small logs

grep -r FAIL logs | sort
grep -rl FAIL logs | sort
logs/a.log:pump-7 FAIL
logs/c.log:pump-3 FAIL
logs/a.log
logs/c.log

Worked example 3

Warden Rao wants the failures from 08:30 onwards, and their number. Each line of the log starts with its time.

What we have: the log, and the times 08:30 to 08:59

What we need: the failure lines from 08:30 on, and a count

The plan: a line from 08:30 on starts with 08:3, 08:4 or 08:5, so the pattern is ^08:[345]; a second grep keeps the failures; -c counts

In a folder with notes.txt and station.log, the log shown at the top of this lesson

grep '^08:[345]' station.log | grep FAIL
grep '^08:[345]' station.log | grep -c FAIL
08:30 pump-1 FAIL low pressure
08:35 pump-7 FAIL blocked valve
08:45 pump-3 FAIL low pressure
3
  1. The first grep chooses the time, the second the kind of line. Two simple greps in a pipe are easier to read than one clever pattern.

There are 3 failures from 08:30 on, at 08:30, 08:35 and 08:45.

Check: the log shows the failures at those three times, and the count agrees.

A path that fails: grep '08:3' station.log. With no ^ the pattern may match anywhere in a line, and it also leaves out 08:40 and 08:45.

When you are stuck: grep finds too much, too little, or nothing

Too much: the pattern matches inside longer words. Add -w, or anchor it with ^ or $.

Nothing: check the capitals, or add -i. Check that the pattern is in single quotes.

A strange message about a missing file: a space in an unquoted pattern made two words, and grep took the second for a file name.

Not sure what matched? Add -o to print only the matching parts.

Your turn

grep -c OK station.log
grep -v -c OK station.log
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
4
6
  1. Four lines contain OK.
  2. -v counts the lines that do not: the other six.

It prints 4, then 6.

Which grep keeps the lines that end in pressure?Tap to reveal
  1. $ means the end of the line.
  2. Quote the pattern.

grep 'pressure$' station.log.

What exit status does grep give when it finds no line at all?Tap to reveal
  1. 0 is found, 2 is an error.

1.

Did you know?

grep skips most of the bytes

GNU grep is fast because it does not look at every byte. Mike Haertel, its original author, explained in August 2010 that it uses the Boyer-Moore method, which looks first for the last letter of the word sought. A lookup table then says how far ahead it can skip whenever a letter does not match. Its second trick, Haertel wrote, is to run very few instructions for each byte it does look at.

Why it fits here: It answers this topic's question: grep skips ahead through a file instead of reading every byte.

Source: Mike Haertel: why GNU grep is fast (freebsd-current mailing list)

Two old names for grep

grep -E and grep -F were once separate commands. The GNU grep manual explains that Seventh Edition Unix had egrep and fgrep, which suited the small computers of the 1970s. POSIX called them obsolescent in 1992 and removed them in 2001. GNU grep deprecated them in 2007, and since version 3.8 in 2022 they print a warning. The manual plans to remove them entirely, so write grep -E.

Why it fits here: It explains the -E of this topic's grep: it replaces the old command egrep, which now prints a warning.

Source: GNU grep manual: What happened to egrep and fgrep?

In one line

grep keeps the lines that match a pattern: -c counts, -v inverts, -n numbers, -i ignores capitals, -w and -x match whole words or lines, -r searches a folder. Patterns are regular expressions: ^ start, $ end, . any one character, * repeats.

Sorting and counting

At a glance

A pile of exam papers is easy to search once it is in order: papers with the same name end up together, and counting them is quick.

The command sort orders lines as text, sort -n as numbers, and sort -r in reverse; -t and -k sort by a column. The command uniq removes repeats that sit next to each other, so sort comes first, and uniq -c counts each line. Together, sort, uniq -c and sort -rn rank anything by how often it appears.

Take a guess: Can one file sort into two different orders on two computers?

A pile of exam papers is easy to search once it is in order: the papers with the same name end up together, and counting them is quick. The commands sort and uniq do that for lines of text.

sort

In a folder with fruit.txt: mango, apple, cherry and banana, one a line

sort fruit.txt
sort -r fruit.txt
apple
banana
cherry
mango
mango
cherry
banana
apple

By default sort compares lines as text, one character at a time. For words that is right. For numbers it is not, because as text 100 comes before 9, the same way that apple comes before banana. The option -n compares the lines as numbers:

printf writes 10, 9 and 100, one a line

printf '10\n9\n100\n' > n.txt
sort n.txt
sort -n n.txt
sort -rn n.txt
10
100
9
9
10
100
100
10
9

Lines are often made of columns. The option -t says what separates the columns, and -k says which column to sort by. Here the separator is a comma, and the second column holds numbers:

printf writes three lines of a small table into pumps.csv

printf 'north,3,ok\nsouth,12,slow\neast,7,ok\n' > pumps.csv
sort -t, -k2 -n pumps.csv
north,3,ok
east,7,ok
south,12,slow

uniq

The command uniq removes repeated lines, but only when they sit next to each other. That is the catch: on unsorted lines it misses the repeats that are apart. So it nearly always comes after sort:

printf writes b, a, b, a and c, one a line

printf 'b\na\nb\na\nc\n' > x.txt
uniq x.txt
sort x.txt | uniq
b
a
b
a
c
a
b
c

With -c, uniq counts each run of equal lines and prints the count in front. With -d, it shows only the lines that were repeated. And sort -u sorts and keeps one of each in a single step:

In a folder with x.txt: b, a, b, a and c, one a line

sort x.txt | uniq -c
sort x.txt | uniq -d
sort -u x.txt
      2 a
      2 b
      1 c
a
b
a
b
c
WrittenIt does
sortorders lines as text
sort -norders them as numbers
sort -rreverses the order
sort -t, -k2sorts by the second column, where commas separate the columns
sort -usorts and keeps one of each
uniqremoves repeats that sit next to each other
uniq -ccounts each run of equal lines
uniq -dshows only the repeated lines

Worked example 4

Here is the warden's question from the scene: which pump fails most? Build the answer from the log, one step at a time, ending with one line.

What we have: a log where each failure line holds the pump's name as its second word

What we need: the pump with the most failures, and how many

The plan: keep the failures with grep, and cut out the second word, the pump, with cut, which the next section explains. Sort, so that equal names sit together. Count each run with uniq -c. Sort the counts as numbers, largest first, and keep the top line

In a folder with notes.txt and station.log, the log shown at the top of this lesson

grep FAIL station.log | cut -d' ' -f2 | sort | uniq -c | sort -rn
      3 pump-7
      2 pump-3
      1 pump-1
  1. Every pump that failed is there, with its count. Now keep only the first line:

In a folder with notes.txt and station.log, the log shown at the top of this lesson

grep FAIL station.log | cut -d' ' -f2 | sort | uniq -c | sort -rn | head -n 1
      3 pump-7
  1. This pipe is worth learning by heart. With any log in place of this one, it counts how often each thing appears and puts the most common first.

pump-7 fails most, with 3 failures.

Check: the log shows pump-7 failing at 08:05, 08:15 and 08:35.

A path that fails: leaving out the first sort. uniq -c then counts only runs of neighbours, so pump-7 appears more than once, each time with a smaller count.

When you are stuck: sort or uniq gives an odd order or odd counts

Numbers in a strange order: add -n.

uniq left repeats in: they were not next to each other. Sort first.

The wrong column was used: check -t, the separator, and -k, the column number.

Capital letters sorted apart from small ones: sort -f ignores capitals.

Your turn

printf '3\n20\n100\n' | sort -n | head -n 1
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
3
  1. sort -n compares the lines as numbers.
  2. The smallest, 3, comes first.

It prints 3.

Why must uniq usually come after sort?Tap to reveal
  1. uniq only removes repeats that are next to each other.

Because sort puts equal lines together, so uniq can find every repeat.

Which pipe counts how many times each line of a file appears, most common first?Tap to reveal
  1. sort, then uniq -c, then sort again, by number, in reverse.

sort file | uniq -c | sort -rn.

Did you know?

Six commands and a famous review

The pipe sort, uniq -c, sort -rn has a famous ancestor. In June 1986, Jon Bentley's column in Communications of the ACM asked for a program that prints the k most common words in a text. Don Knuth answered with a program in his WEB system for literate programming. Doug McIlroy of Bell Labs reviewed it with a script of six commands: tr twice, then sort, uniq -c, sort -rn and sed. It was written on the spot and worked on the first try.

Why it fits here: It shows the reach of this topic's pipe sort, uniq -c, sort -rn: six small commands answered a problem set for a whole program.

Source: Jon Bentley, Don Knuth and Doug McIlroy: A Literate Program (Communications of the ACM)

One file, two orders

The same file can sort in two orders on two computers. The GNU coreutils FAQ explains that with LANG set to en_US.UTF-8, sort folds case and ignores punctuation, because that locale, the computer's language setting, asks for it. To get the standard order, set LC_ALL to C. Then sort uses the traditional tables for US-ASCII, and case is no longer folded.

Why it fits here: It explains why this topic's sort may mix or separate capitals: the computer's locale decides, and LC_ALL=C gives the standard order.

Source: GNU Coreutils FAQ: Sort does not sort in normal order!

In one line

sort orders lines as text, -n as numbers, -r in reverse, and -t with -k by a column. uniq removes neighbouring repeats, so sort first; uniq -c counts each one. The pipe sort, uniq -c, sort -rn ranks anything by how often it appears.

Cutting and changing text

At a glance

Pipes often need to change the text on its way: take one column out, swap some characters, or replace a word. Three tools cover most of that work.

The command cut keeps columns, chosen by a separator with -d and -f, or by position with -c. The command tr swaps, deletes or squeezes characters. The command sed edits lines as they flow: s/old/new/ replaces, d deletes, -n with p prints chosen lines, and -i changes the file itself, with no undo.

Take a guess: What kind of file was sed first made for?

Pipes often need to change the text on its way: take one column out, swap some characters, or replace a word. Three tools cover most of it. The command cut takes out columns, tr swaps characters, and sed edits lines.

cut: columns

The option -d says what separates the columns, its delimiter, and -f says which fields, or columns, to keep. In the station log the columns are separated by spaces, and the pump is the second field:

In a folder with notes.txt and station.log, the log shown at the top of this lesson

cut -d' ' -f2 station.log | head -n 3
pump-3
pump-7
pump-2

Fields can be listed with commas, or as a range. The option -c keeps characters by position instead, which suits text where every line has the same layout, such as the times at the start of the log:

In a folder with pumps.csv, a small table of three lines: north,3,ok and south,12,slow and east,7,ok

cut -d, -f1 pumps.csv
cut -d, -f1,3 pumps.csv
cut -c1-5 pumps.csv
north
south
east
north,ok
south,slow
east,ok
north
south
east,

Look at the last line of that answer. The first five characters of east,7,ok are east and the comma, as east is shorter than north. Character positions only work when every line lines up.

tr: characters

The command tr, short for translate, reads its input and swaps characters: each character of the first set becomes the matching character of the second. With -d it deletes characters, and with -s it squeezes a run of the same character into one:

echo hello | tr a-z A-Z
echo 'pump-7' | tr -d '-'
echo 'a    b   c' | tr -s ' '
HELLO
pump7
a b c

That last trick rescues cut. To cut, two spaces in a row mean an empty column between them, so a line with uneven spaces gives an empty field. Squeeze the spaces first:

echo 'a    b   c' | cut -d' ' -f2
echo 'a    b   c' | tr -s ' ' | cut -d' ' -f2

b

sed: editing lines as they flow

The command sed, short for stream editor, changes text line by line as it passes through. Its most used command is s/old/new/, which replaces the first old in each line with new. Add g after the last slash to replace every one:

In a folder with notes.txt and station.log, the log shown at the top of this lesson

sed 's/FAIL/BROKEN/' station.log | head -n 2
echo 'aaa' | sed 's/a/b/'
echo 'aaa' | sed 's/a/b/g'
08:00 pump-3 OK
08:05 pump-7 BROKEN low pressure
baa
bbb

sed can also pick lines. With -n it prints nothing unless told to, and p tells it to print; d deletes lines. In front of either goes the line number, a range of numbers, or a pattern between slashes:

In a folder with notes.txt and station.log, the log shown at the top of this lesson

sed -n '2,3p' station.log
sed '/OK/d' station.log | wc -l
sed -n '/pump-1 /p' station.log
08:05 pump-7 FAIL low pressure
08:10 pump-2 OK
6
08:30 pump-1 FAIL low pressure

Normally sed only prints the changed text, and the file stays as it was. The option -i edits the file itself, in place. There is no undo, so try the command without -i first, and look at what it prints:

In a folder with notes.txt and station.log, the log shown at the top of this lesson

sed -i 's/pump one/pump 1/' notes.txt
cat notes.txt
pump 1
pump two
valve
WrittenIt does
cut -d' ' -f2keeps the second space-separated field
cut -d, -f1,3keeps fields 1 and 3, separated by commas
cut -c1-5keeps characters 1 to 5
tr a-z A-Zturns small letters into capitals
tr -d '-'deletes every dash
tr -s ' 'squeezes runs of spaces into one
sed 's/a/b/g'replaces every a with b
sed -n '2,3p'prints only lines 2 and 3
sed '/OK/d'deletes the lines that contain OK

Worked example 5

Warden Rao wants a short repair list: one line for each failure, in the form pump-7: low pressure, with nothing else on the line.

What we have: the failure lines, each a time, a pump, FAIL and a reason

What we need: lines such as pump-7: low pressure

The plan: keep the failures with grep; cut out field 2, the pump, and fields 4 onwards, the reason; then sed puts a colon after the first word

In a folder with notes.txt and station.log, the log shown at the top of this lesson

grep FAIL station.log | cut -d' ' -f2,4- | sed 's/ /: /'
pump-7: low pressure
pump-7: low pressure
pump-3: blocked valve
pump-1: low pressure
pump-7: blocked valve
pump-3: low pressure
  1. In -f2,4- the 4- means field 4 and everything after it. The s command without g changed only the first space, which sits after the pump's name.

Six lines, from pump-7: low pressure to pump-3: low pressure.

Check: there are six failures in the log, and six lines here.

A path that fails: sed 's/ /: /g'. The g changes every space, so the reason becomes low: pressure as well.

When you are stuck: cut, tr or sed changes the wrong thing

cut gives empty fields: the columns are separated by more than one space. Squeeze them with tr -s ' ' first.

sed changed only the first match in each line: add g.

sed changed too much: the pattern also matches elsewhere. Make it longer, or anchor it with ^ or $.

Before sed -i, run the same sed without -i and read what it prints.

Your turn

echo 'north,3,ok' | cut -d, -f2
echo 'pump' | tr a-z A-Z
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
3
PUMP
  1. The second comma-separated field is 3.
  2. tr turns each small letter into its capital.

It prints 3, then PUMP.

Which sed command replaces every OK with GOOD?Tap to reveal
  1. s/old/new/ replaces; g makes it every one.

sed 's/OK/GOOD/g'.

Why can cut -d' ' -f2 print an empty line?Tap to reveal
  1. Two spaces in a row have an empty field between them.

Because the separator came twice in a row, so field 2 is empty.

Did you know?

Made for files too big to edit

sed was built for files too big for an editor. In a manual dated 15 August 1978, Lee E. McMahon of Bell Laboratories called it a non-interactive editor, and the first use the manual named was for files too large for comfortable editing by hand. Only a few lines of input sit in memory at a time, and no temporary files are used. So the only limit is that the input and the output fit on the disk together.

Why it fits here: It answers this topic's question: sed was first meant for files too large to edit by hand, which is why it works line by line.

Source: Lee E. McMahon: SED, A Non-interactive Text Editor

Any character can be the slash

The slashes of sed's s command are not fixed. The GNU sed manual says they may be replaced by any other single character within one s command. That helps with paths: s|/usr/local|/opt| changes a path with no backslashes, while the slash form needs s/\/usr\/local/\/opt/. Inside the pattern, the chosen character needs a backslash only where it appears itself.

Why it fits here: It adds a trick to this topic's s/old/new/: with another separator, paths full of slashes need no backslashes.

Source: GNU sed manual

In one line

The command cut keeps columns, by a separator with -d and -f, or by position with -c. The command tr swaps, deletes or squeezes characters. The command sed edits lines as they flow: s/old/new/ replaces, -n with p prints chosen lines, d deletes, and -i edits the file itself.

Lines into arguments: xargs

At a glance

Some commands read standard input, and pipes suit them: grep, sort, wc and cut. Others never read it. They only take arguments, the words written after them, as rm, mkdir, touch and cp do.

The command xargs turns lines of input into arguments for such a command. With -n 1 it runs the command once for each item, and with -I{} it puts each line in the place of {}. Names with spaces fall apart at the spaces, so use find -print0 with xargs -0, or let find run the command itself.

Take a guess: Why can rm * fail in a folder that holds a million files?

Some commands read standard input, and pipes suit them: grep, sort, wc, cut. Others never read it. They only take arguments, the words written after them: rm, mkdir, touch, cp. Piping into one of those does nothing useful:

echo notes.txt | rm
rm: missing operand
Try 'rm --help' for more information.

The command xargs is the adapter. It reads words from its standard input, and adds them as arguments to the command you name. So echo a.txt b.txt | xargs rm runs rm a.txt b.txt:

touch a.txt b.txt keep.txt
echo a.txt b.txt | xargs rm
ls
keep.txt

A list of names in a file becomes a list of arguments. The option -n 1 runs the command once for each item, and -I{} puts each item wherever {} appears:

printf writes north and south, one a line, into names.txt

printf 'north\nsouth\n' > names.txt
xargs mkdir < names.txt
xargs -n 1 echo pump < names.txt
xargs -I{} touch {}/today.log < names.txt
ls north south
pump north
pump south
north:
today.log

south:
today.log

Read the third line as: for each name, run echo pump and the name. The fourth runs touch once for each name, with the name put inside the path.

Names with spaces

xargs splits its input at spaces and new lines, so a name with a space in it falls apart into two arguments:

In a folder holding t, with the files a b.tmp and c.tmp

find t -name '*.tmp' | xargs rm
rm: cannot remove 't/a': No such file or directory
rm: cannot remove 'b.tmp': No such file or directory

There are two safe ways. find can end each name with an invisible zero character instead of a new line, using -print0, and xargs -0 splits only at those. Or find can run the command itself with -exec ... {} +, which hands it many names at once and needs no xargs at all:

In a folder holding t and u, each with the files a b.tmp and c.tmp

find t -name '*.tmp' -print0 | xargs -0 rm
find u -name '*.tmp' -exec rm {} +
ls t u
t:

u:

Both folders are now empty: every file went, spaces and all. The exit status of xargs is 0 when every run succeeded, and 123 when any of them failed.

WrittenIt runs
echo a b | xargs rmrm a b
xargs mkdir < list.txtmkdir with every name in the file
xargs -n 1 cmdcmd once for each item
xargs -I{} cmd {}/xcmd once for each line, put in place of {}
find ... -print0 | xargs -0 cmdcmd with names that may hold spaces
find ... -exec cmd {} +the same, with no xargs

Worked example 6

A file named pumps.txt lists the pumps that need a repair folder, one a line. Make a folder for each, then put an empty file named repair.log inside each folder, and show the result.

What we have: a list of names in pumps.txt

What we need: a folder for each name, each holding repair.log

The plan: mkdir does not read input, so xargs gives it the names; then xargs with -I{} runs touch once for each name, with the name in the path

In a folder with pumps.txt, which lists pump-1, pump-3 and pump-7

xargs mkdir < pumps.txt
xargs -I{} touch {}/repair.log < pumps.txt
find . -name repair.log | sort
./pump-1/repair.log
./pump-3/repair.log
./pump-7/repair.log
  1. Two commands made three folders and three files, and the list could have held three hundred.

Each of pump-1, pump-3 and pump-7 now holds a repair.log.

Check: find lists one repair.log in each of the three folders.

A path that fails: cat pumps.txt | mkdir. mkdir never reads its input, so it stops at once with missing operand.

When you are stuck: xargs does something strange

missing operand: the command does not read input. Put xargs in front of it.

Names broken at spaces: use find -print0 with xargs -0, or find -exec ... {} +.

Not sure what xargs will run? Put echo after it: xargs echo rm shows the command line, and runs nothing.

A status of 123: one of the commands that xargs ran failed. Run them by hand to see which.

Your turn

echo one two three | xargs -n 1 echo
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
one
two
three
  1. xargs reads three words.
  2. -n 1 runs echo once for each.

It prints one, two and three, each on its own line.

Why does echo old.txt | rm fail?Tap to reveal
  1. rm takes arguments; it never reads standard input.

Because rm does not read its input, so it got no file name.

How would you remove every .tmp file found below this folder, when some names may hold spaces?Tap to reveal
  1. Zero characters keep names whole.
  2. Or let find run rm itself.

find . -name '*.tmp' -print0 | xargs -0 rm, or find . -name '*.tmp' -exec rm {} +.

Did you know?

Argument list too long

A command line has a size limit, and xargs is built to stay under it. The Linux manual for execve says that on most machines the arguments and environment together may take at most a quarter of the stack size limit, and one argument at most 32 pages. Past that, a program cannot start: execve fails with the error E2BIG, whose message is Argument list too long. xargs builds each command line only up to the system's limit, and runs the command as many times as needed.

Why it fits here: It answers this topic's question: a million names can overflow one command line, and xargs splits the list to fit.

Sources: Linux man-pages: execve(2); Linux man-pages: errno(3); Linux man-pages: xargs(1)

Several commands at once

xargs can run commands side by side. The xargs manual says its -P option runs up to the given number of processes at a time, where the default is 1, and -P 0 runs as many as possible. It adds a warning: use -n or -L with -P, or chances are that only one command will run. So xargs -n 1 -P 4 gzip keeps four copies of gzip working at once, each on its own file.

Why it fits here: It adds speed to this topic's xargs: with -P it runs several copies of a command at the same time.

Source: Linux man-pages: xargs(1)

In one line

Commands such as rm, mkdir and touch take arguments and never read standard input; xargs turns lines of input into their arguments. -n 1 runs once per item and -I{} puts each line in place. For names with spaces, use -print0 with -0, or find -exec.

Where it is used

Pipes are how people who run servers answer questions quickly. Here is where each idea of this lesson does its work.

What you learnedWhere it is usedA real example
> file and >>keeping results and logsa nightly job adding a line to a report
2> /dev/nullhiding expected noisea check that may fail harmlessly
pipesanswers in one linethe ten busiest pages of a website, from its log
grepsearching logs and codeevery line of a project that uses a function
sort | uniq -c | sort -rncounting and rankingwhich visitor sends the most requests
cut, tr, sedcleaning textone column of a spreadsheet saved as CSV
sed -iediting settings fileschanging one value in a server's settings
xargsacting on a listremoving every file that a find turned up

Mistakes and debugging

These are the slips that people meet most often with redirection and pipes. Every output below is the real one, from the code shown.

1. Sorting a file into itself

In a folder with notes.txt and station.log, the log shown at the top of this lesson

sort notes.txt > notes.txt
wc -c notes.txt
0 notes.txt

The shell empties notes.txt for the > before sort even starts, so sort reads an empty file. The notes are gone. The fix: write to a new file, sort notes.txt > sorted.txt, and rename it afterwards if you like.

2. > where >> was meant

echo "first check" > log.txt
echo "second check" > log.txt
cat log.txt
second check

Each > empties the file first. The fix: >> to add a line.

3. 2>&1 in the wrong place

ls nothing.txt 2>&1 > out.txt
ls: cannot access 'nothing.txt': No such file or directory

Redirections are read from left to right. Here 2>&1 sent errors to where output was going at that moment, the screen, and only then did > move the output into the file. The fix: ls nothing.txt > out.txt 2>&1.

4. uniq without sort

printf 'b\na\nb\n' | uniq -c
      1 b
      1 a
      1 b

The two b lines are not neighbours, so each is counted alone. The fix: sort | uniq -c.

5. Numbers sorted as text

printf '9\n10\n' | sort
10
9

As text, 10 comes before 9, because 1 comes before 9. The fix: sort -n.

6. A pattern with a space and no quotes

In a folder with notes.txt and station.log, the log shown at the top of this lesson

grep low pressure station.log
grep: pressure: No such file or directory
station.log:08:05 pump-7 FAIL low pressure
station.log:08:15 pump-7 FAIL low pressure
station.log:08:30 pump-1 FAIL low pressure
station.log:08:45 pump-3 FAIL low pressure

grep searched for low, in two files: one named pressure, which does not exist, and station.log. The fix: grep 'low pressure' station.log.

7. Piping into a command that does not read

echo old.txt | rm
rm: missing operand
Try 'rm --help' for more information.

rm takes arguments, and never reads its input. The fix: echo old.txt | xargs rm, or just rm old.txt.

The debugging corner: one step at a time

When a pipe gives a wrong answer, take it apart. Run the first command alone. Add the next | and look again. Put | head on the end of a step to see a few lines. The step where the text first looks wrong is where the mistake is.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

The lesson in code

grep FAIL station.log > fails.txt         # output into a file
echo "checked" >> fails.txt               # add a line
ls nothing.txt 2> /dev/null || echo none  # hide an error
wc -l < fails.txt                         # feed a file in
grep -c OK station.log                    # count matches
grep '^08:4' station.log | grep -v OK     # chain two filters
cut -d' ' -f2 station.log | sort | uniq -c | sort -rn | head -n 1
sed -n '1p' station.log | tr a-z A-Z
echo fails.txt | xargs wc -l
none
7
4
08:45 pump-3 FAIL low pressure
      4 pump-7
08:00 PUMP-3 OK
7 fails.txt
When you seeIt meansLook at
an error on screen while > was usederrors travel on stream 22> or 2>&1
a file suddenly empty> emptied it first>>, or a new file name
missing operand after a |the command does not read inputxargs
a count split into several linesuniq without sortsort | uniq -c
10 before 9numbers sorted as textsort -n
grep: word: No such file or directoryan unquoted space in a patternsingle quotes
an empty field from cuttwo separators in a rowtr -s ' '
a pipe that seems to hanga command waiting for typed inputCtrl+C, and give it a file

The story: From each to the next

You connect them. One machine keeps only the failures. The next cuts out the pump's number. The next sorts the numbers, so that equal ones sit together; the next counts each run; and the last sorts the counts, largest first. What comes out of each goes straight into the next, with nothing left lying about on the floor.

One line comes out at the end: pump seven, with more failures than the next three put together.

The warden sends a crew to pump seven. Corin looks at the single line, then at his tally sheet. "Tuesday," he says quietly, and puts it in the stove.

Reagents gathered: standard output, redirection, pipe, grep, sort, uniq.

Sources

  • GNU Bash Reference Manual (GNU Free Documentation License 1.3 or later (the manual's copying notice, read 2026-11-06); facts and ideas only)
  • GNU Coreutils manual (GNU Free Documentation License 1.3 or later (the manual's copying notice, read 2026-11-06); facts and ideas only)
  • GNU grep and GNU sed manuals (GNU Free Documentation License 1.3 or later (each manual's copying notice, read 2026-11-06); facts and ideas only)