Techniquecore
Unix text processing pipeline
Also called shell pipeline, pipes and filters in the shell, text filter pipeline, Unix pipeline, software tools approach.
Solve a text task with a chain of small filter programs that each read lines from standard input and write lines to standard output, connected with the shell operator |.
Purpose
A Unix text processing pipeline does a text task with a chain of small programs. Each program is a filter: it reads lines from its standard input and writes lines to its standard output. The shell operator | connects two programs: "The standard output of command1 shall be connected to the standard input of command2".1 The GNU Coreutils manual says of programs that do one thing: "Such programs are simpler to design, write, and get right". It also says: "By combining several special purpose programs, you could accomplish a specific task that none of the programs was designed for".2
The programs of a pipeline run at the same time. Bash says: "Each command in a multi-command pipeline, where pipes are created, is executed in its own subshell".3 A program reads the lines of the program before it while that program writes them, so most stages process a stream (see Process a large text file as a stream). A stage such as sort is different: it can write its first line only after it reads its last line, because the last input line can be the first output line.
Steps
- Write the task as a series of steps from lines to lines. For a list of the most frequent words: put each word on its own line, change the words to lower case, put equal words next to each other, count each group of equal words, and sort by the count.
- Find a filter for each step.
grepselects lines,sedandtrchange text,cutandawkselect fields,sortsorts,uniqremoves or counts repeated lines,headandtailselect the first or the last lines, andwccounts. If no filter does a step, write a small program that reads standard input and writes standard output. - Connect the filters with
|. In a script, put each stage on its own line, with the|at the end of the line before it. Then each stage can have a comment. - Set the locale.
sortcompares lines with the rules of the locale: the comparison "shall be performed using the collating sequence of the current locale".4 A range such asA-Zintralso depends on the locale. SetLC_ALL=Cwhen the result must not depend on the locale of the user. - Make the exit status show a failure of each stage. Bash says: "The exit status of a pipeline is the exit status of the last command in the pipeline, unless the pipefail option is enabled".3 The POSIX option
set -o pipefailtells the shell to "Derive the exit status of a pipeline from the exit statuses of all of the commands in the pipeline, not just the last (rightmost) command".1 - Build the pipeline one stage at a time. Run the first stage on a small input and look at the output. Then add the next stage, and look at the output again. When each stage is correct, run the pipeline on the full input.
Example
In Bash. The pipeline prints the four most frequent words of a short text, with the count of each word. The first tr has the options -c and -s. With -c, the set of characters to change is all the characters that are not letters. With -s, "repeated sequences of the same character shall be replaced by one occurrence of the same character".5 So each run of characters that are not letters becomes one LF, and each word is on its own line. uniq -c puts a count before each group of equal lines, and uniq can do this only because sort put the equal lines next to each other. The second sort puts the highest count first, and sorts equal counts by the word:
export LC_ALL=C # byte order for sort, and ASCII letters for tr
text='The cat sat on the mat. The dog sat on the log.
A cat and a dog: the cat ran.'
printf '%s\n' "$text" |
tr -cs 'A-Za-z' '\n' | # each run of other characters becomes one LF
tr 'A-Z' 'a-z' | # lower case
sort | # equal words become adjacent
uniq -c | # count each run of equal lines
sort -k1,1nr -k2,2 | # most frequent first, then by word
head -n 4
5 the
3 cat
2 a
2 dog
The example file does the same in Python. It starts each stage with subprocess.Popen and connects the stages with pipes, with no shell.
import os
import subprocess
import tempfile
text = 'The cat sat on the mat. The dog sat on the log.\nA cat and a dog: the cat ran.\n'
env = {'LC_ALL': 'C', 'PATH': os.environ['PATH']}
# tr -cs 'A-Za-z' '\n' < words.txt | tr 'A-Z' 'a-z' | sort | uniq -c, with no shell
commands = [['tr', '-cs', 'A-Za-z', '\n'], ['tr', 'A-Z', 'a-z'], ['sort'], ['uniq', '-c']]
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, 'words.txt')
with open(path, 'w') as f:
f.write(text)
with open(path) as source:
processes = []
stdin = source
for command in commands:
p = subprocess.Popen(command, stdin=stdin, stdout=subprocess.PIPE, env=env)
if processes:
processes[-1].stdout.close() # only p reads this pipe now
processes.append(p)
stdin = p.stdout
output = processes[-1].communicate()[0]
statuses = [p.wait() for p in processes]
print(output.decode(), end='')
print('statuses:', statuses)
2 a
1 and
3 cat
2 dog
1 log
1 mat
2 on
1 ran
2 sat
5 the
statuses: [0, 0, 0, 0]
The program starts one process for each stage with subprocess.Popen, and gives the standard output of each process to the next one as its standard input. After it starts a stage, it closes its own copy of the read end of the pipe before it, so that only the new stage reads that pipe. communicate reads the output of the last stage, and wait gives the status of each stage, as PIPESTATUS does in Bash. The program passes each argument as an item of a list, so no shell splits or changes the arguments.
When to use
Use a pipeline for a task on lines of text that is a series of simple steps: a report from a log file, a count of the values in a column, a list of the distinct values, or a quick check of a data file. Use it also to test an idea before you write a program. See Compute word frequencies for the same task in many languages.
Do not use a pipeline when one record of the data can be on more than one line, as in JSON or in a CSV file with an LF in a quoted field (see Delimited text), because each filter reads one line as one record. Do not use it when the steps need a complex state, or when the program must handle each error in its own way. Then write the task as a program in one language.
Pitfalls
-
uniqfinds only adjacent repeated lines. POSIX says: "Repeated lines in the input shall not be detected if they are not adjacent."6 Withoutsortbefore it,uniq -ccounts each run of equal lines, not each distinct line. The option-ctellsuniqto "Precede each output line with a count of the number of times the line occurred in the input."6 In the block, the linebcomes two times, but not next to itself:export LC_ALL=C echo 'uniq -c only:' printf 'b\na\nb\n' | uniq -c echo 'sort | uniq -c:' printf 'b\na\nb\n' | sort | uniq -cOutput uniq -c only: 1 b 1 a 1 b sort | uniq -c: 1 a 2 b -
The exit status hides a failure. Without
pipefail, the status of a pipeline is the status of its last command.3 In the block,sortfails because the file does not exist, butwcsucceeds, so the status is 0. Withpipefail, the status is 2, the status ofsort. Butpipefailcan also report a failure when there is no error.headstops after two lines, and thenseqwrites to a pipe that has no reader. Forwrite, POSIX gives the errorEPIPE: "An attempt is made to write to a pipe or FIFO that is not open for reading by any process, or that only has one end open. A SIGPIPE signal shall also be sent to the thread."7 The signal stopsseq. Bash gives the status 128 plus N to a command that a fatal signal with the number N stops.8 The arrayPIPESTATUSholds "a list of exit status values from the commands in the most-recently-executed foreground pipeline".9 Use it to see which stage failed:sort no-such-file.txt 2>/dev/null | wc -l echo "status: $?" set -o pipefail sort no-such-file.txt 2>/dev/null | wc -l echo "status with pipefail: $?" seq 1 1000000 | head -n 2 echo "statuses: ${PIPESTATUS[*]}"Output 0 status: 0 0 status with pipefail: 2 1 2 statuses: 141 0 -
A variable that a stage sets is lost. Each stage runs in its own subshell, so a
whileloop at the end of a pipeline changes a copy of the variable.3 After the pipeline, the variable has its old value. Bash says that when the optionlastpipeofshoptis on and job control is not active, "the last element of a pipeline may be run by the shell process".3 In the block, which runs as a script, the second loop runs in the shell process, so the count stays after the loop:count=0 printf 'a\nb\nc\n' | while IFS= read -r line; do count=$((count + 1)) done echo "after the pipeline: $count" shopt -s lastpipe # the shell runs the last stage, when job control is off count=0 printf 'a\nb\nc\n' | while IFS= read -r line; do count=$((count + 1)) done echo "with lastpipe: $count"Output after the pipeline: 0 with lastpipe: 3 -
Output waits in a buffer. A C program buffers its output in blocks when the output is a pipe: "stdin and stdout shall be fully buffered if and only if" "the file descriptor associated with the stream is determined not to be associated with an interactive device".10 With a file, this is not a problem. With an input that does not end, as in Follow a growing file, the next stage can get no lines for a long time. GNU
grephas the option--line-bufferedto "Use line buffering for standard output, regardless of output device."11 -
The locale changes the order. The same pipeline can give a different order on a different computer, because
sortuses "the collating sequence of the current locale".4 SetLC_ALL=Cin the script, as in the example, when the output must be the same on each computer.
Tools that do it
| Tool | Step | See |
|---|---|---|
grep |
Select the lines that match a pattern | Filter lines that match a pattern |
sed |
Change text with a regular expression, delete lines | Remove lines from a file |
tr |
Change, delete or squeeze characters | Compute word frequencies |
cut, awk |
Select fields | Delimited text |
sort |
Sort lines | Sort the lines of a file |
uniq |
Remove or count adjacent repeated lines | Remove duplicate lines |
head, tail |
Select the first or the last lines | Print the first and last lines of a file |
wc |
Count lines, words and bytes | Count the lines of a file |
Python subprocess |
Start a pipeline from a program, with no shell | Run a subprocess |
The Python documentation shows a pipeline with Popen, and says: "The p1.stdout.close() call after starting the p2 is important in order for p1 to receive a SIGPIPE if p2 exits before p1."12 For a pipeline of filters inside one program, with no processes, see Collection pipeline.
References
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), Shell Command Language, 2.9.2 Pipelines; set, -o pipefail
- GNU Coreutils manual, Toolbox introduction, Opening the Software Toolbox
- Bash Reference Manual, Pipelines, 3.2.3 Pipelines
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), sort, DESCRIPTION
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), tr, OPTIONS, -c and -s
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), uniq, DESCRIPTION; OPTIONS, -c
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), write, ERRORS, EPIPE
- Bash Reference Manual, Exit Status, 3.7.5 Exit Status
- Bash Reference Manual, Bash Variables, PIPESTATUS
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), stderr, stdin, stdout, DESCRIPTION
- GNU Grep manual, 2.1.7 Other Options, --line-buffered
- The Python Standard Library, subprocess, Subprocess management, Replacing shell pipeline
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 1SGR7A Edit this page History Report an error Markdown