Pipes in Linux: | and the sort, uniq, cut filters

Updated November 1, 2026

A pipe joins commands with | so the output of one becomes the input of the next.

Common cases

grep 404 access.log | wc -l                # how many 404 lines
cut -d' ' -f1 access.log | sort | uniq -c   # frequency by the first field
... | sort -rn                             # numeric sort, descending
ps aux | grep nginx | grep -v grep         # filter the process list

Sample output

$ cut -d' ' -f1 access.log
10.0.0.7
10.0.0.5
10.0.0.7
10.0.0.9
10.0.0.5
10.0.0.7
$ cut -d' ' -f1 access.log | sort | uniq -c | sort -rn
      3 10.0.0.7
      2 10.0.0.5
      1 10.0.0.9

How it works: small commands, one job each

The Unix idea: each command does one job, reads from standard input and writes to standard output. | joins them: the kernel feeds the left command's output into the right command's input without touching the disk. The classic filters: grep selects lines, cut slices columns, sort orders, uniq -c counts adjacent repeats (so it almost always follows sort), wc -l counts lines. From these blocks you build log analysis on one line.

Common mistakes

The exit status of a pipeline is the status of its last command. grep nosuchthing /etc/hostname | wc -l prints 0 and exits with 0, because wc did fine and the failure of grep was lost along the way. A script that tests such a pipeline never sees the failure. Ask grep -q directly, or turn on set -o pipefail, and the status comes from the first command that failed.

The right side of a pipe runs in a separate process, so variables changed inside it do not survive. The line count=0; cat list.txt | while read line; do count=$((count+1)); done; echo $count prints 0 on a two line file, not 2: the loop counted in its own copy of the variable and the copy died with the process. Feed the file by redirection instead - while read line; do ...; done < list.txt keeps the loop in the current shell.

ps aux | grep nginx finds itself. On a machine with no nginx at all the command still prints a line like student 24 ... grep --color=auto nginx: by the time ps takes its snapshot, grep is already running and lands in the list. Hence the habit of appending grep -v grep. pgrep nginx is cleaner: it reads the process table itself, never adds itself to it, and quietly exits with 1 when nothing matches.

Used in

You need this in the lesson Streams and pipelines. The theory is the chapter Streams, redirection, pipelines.

See also

Redirection > and >>, The grep command.

Try it

Open the sandbox: a real throwaway Linux terminal in your browser. Run the commands above by hand - the container is deleted when you leave.