Working with Text
Single-page view · as markdown
Text Streams
Peios / Using Peios / Working with Text
The text utilities read a stream of bytes and divide it into records, usually one record for each line. Each command then does one thing to those records: shows some of them, combines them, reorders them, or changes their characters. You can join the commands in a pipeline, where each one reads the previous command's output. A few rules decide whether the result means what you expect.
Records and delimiters #
Most commands end a record at each newline. Commands that select fields, such
as cut and join, also split each record at a delimiter character you
choose. A delimiter is only a character, not a parsing rule: these commands
don't understand quoted values or escaped delimiters, so use a parser for
formats that have them.
Commands that count bytes rather than lines or characters can split a character that takes more than one byte. Use line or character counts for text that people will read.
Keep input and output separate #
The shell opens an output file before the command starts. Redirecting output to the file a command is reading empties that file before the command reads it:
Always write to a different file, check it, and only then replace the original. A command that exits with an error can leave partial output, so check its exit status, not only whether the output file exists.
Order and comparison rules #
Some commands compare records with each other. uniq compares neighboring
lines only, so sort first to bring equal lines together. join and comm
need both inputs sorted with the same rules.
Sorting depends on the locale, which sets the language rules for comparing
text. Set the same locale for every command in a pipeline that compares
records. LC_ALL=C gives an ordering by byte value that is the same on every
machine:
LC_ALL=C
Commands for each task #
Choose the page by what you want to do:
- Viewing and Combining Text to read files, select parts of them, and combine or split them.
- Transforming Text to sort, count, translate, and reformat text.
- Verifying Checksums and Encoding Bytes to check that data hasn't changed, or to carry bytes as text.
Viewing and Combining Text
Peios / Using Peios / Working with Text
Use these commands to read text files, pick out the parts you need, and combine or split them. None of them change the files they read; they write their result to standard output. The man page for each command lists every option.
The examples use sample file names such as names.txt. Create those files
first, or substitute your own.
Read a file #
cat writes files to standard output one after another, which also combines
them:
cat -A shows tabs, line endings, and other invisible characters, and
cat -n numbers the lines. For a long file, more shows one screen at a
time: press Space for the next screen, / to search, and
Q to stop. nl prints a numbered copy that leaves blank lines
unnumbered, and tac prints lines from last to first.
Read the start or end #
Show the first two lines of a file:
tail -n 2 progress.log shows the last two lines. Without -n, head shows
10 lines. To watch a log as it grows, use tail -f, which follows the file it
opened. If a program replaces the log with a new file of the same name,
tail -F follows the name instead and keeps going. Press
Ctrl+C to stop. With several files, head and tail
label each one, and the labels become part of the output.
Inspect raw bytes #
When a terminal would hide or reinterpret characters, od shows each byte as
a number:
-tx1 shows one byte per hexadecimal value, and -An hides the offset
column. Repeated rows are collapsed to * unless you add -v.
Select fields #
cut selects fields from each line, split at a delimiter:
A line without the delimiter passes through unchanged unless you add -s.
Combine files #
Choose by what links the lines together:
- By position.
paste names.txt counts.txtputs the first line of each file side by side, then the second, and so on. A missing line shifts every later pair. - By a shared key.
join counts.txt colors.txtcombines lines whose first field matches. Both files must be sorted on that field with the same rules, and a repeated key produces more than one output line. - By membership.
commcompares two sorted files and shows the lines found only in the first, only in the second, or in both.
For join and comm, set the locale to the one you sorted with, for example
LC_ALL=C join counts.txt colors.txt.
Split a file #
Split a file into pieces of two lines each:
The pieces are named piece-aa, piece-ab, and so on, and joining them in
that order with cat restores the original. csplit report.txt '/Section/'
splits at a line that matches a pattern instead. Both commands can overwrite
existing files with the same names, so run them in an empty directory. New
pieces inherit security from their directory.
Commands on this page #
This page covers these commands:
| Command | Use it to | Manual |
|---|---|---|
cat | Write files to output in order | cat(1) |
more | Read a file one screen at a time | more(1) |
nl | Number lines | nl(1) |
tac | Print lines in reverse order | tac(1) |
head, tail | Read the start or end of a file | head(1), tail(1) |
od | Show bytes as numbers | od(1) |
cut | Select fields from each line | cut(1) |
paste | Combine lines by position | paste(1) |
join | Combine lines by a shared key | join(1) |
comm | Compare two sorted files | comm(1) |
split, csplit | Split a file into pieces | split(1), csplit(1) |
Transforming Text
Peios / Using Peios / Working with Text
Use these commands to change the order, characters, or layout of text. Each writes a transformed copy to standard output and leaves its input unchanged. Decide which properties of the text carry meaning before you transform it: a reflow can break code, and a sort loses the original order. The man page for each command lists every option.
The examples use sample file names such as names.txt. Create those files
first, or substitute your own.
Sort and count records #
Sort lines as numbers rather than as text:
LC_ALL=C
Without -n, sort compares text, so 12 sorts before 3. Use a key field
when each line holds both a name and a value. To write the result over the
input, use the command's output option rather than shell redirection, which
would empty the input first. See sort(1).
uniq compares neighboring lines only, so sort first to count every repeated
value:
LC_ALL=C |
wc -l -w -c names.txt counts lines, words, and bytes. The line count counts
newline characters, so a last line with no newline isn't counted. Byte and
character counts differ for characters that take more than one byte.
Translate characters #
tr changes or removes characters in standard input:
| LC_ALL=C
tr reads only standard input; it takes no file name. A range such as a-z
doesn't convert letters in every writing system, so keep to ASCII text or use
a tool that understands the language. Quote the character sets so that the
shell doesn't interpret them.
Convert tabs and spaces #
expand -t 4 tabs.txt replaces each tab with the spaces needed to reach the
next tab stop, and unexpand -t 4 spaces.txt turns suitable runs of spaces
back into tabs. Without -t, expand puts tab stops eight columns apart.
Keep the original when tabs carry meaning in the file's format.
Reflow and paginate #
fmt -w 30 notes.txt rejoins the words of each paragraph into lines of at
most 30 characters. Use it for prose only: it changes the line breaks that
code, tables, and markup depend on. fold -s -w 12 breaks long lines without
joining short ones. pr adds page headings and margins for printing, so don't
pass its output to a program that expects the original lines.
Order dependencies #
tsort reads pairs in which the first item must come before the second, and
prints an order that satisfies every pair:
|
If the pairs form a cycle, no order exists and tsort fails; check its exit
status rather than using partial output. Items with no dependency between them
can come out in any order.
Shuffle and index #
shuf names.txt prints the lines in a random order, and can take a sample.
Given a recorded random source, it repeats the same shuffle, which helps in
testing but isn't suitable for choices that must be unpredictable. ptx
builds a keyword index that shows each word with the text around it.
Commands on this page #
This page covers these commands:
| Command | Use it to | Manual |
|---|---|---|
sort | Sort lines | sort(1) |
uniq | Collapse or count repeated neighboring lines | uniq(1) |
wc | Count lines, words, and bytes | wc(1) |
tr | Translate or delete characters | tr(1) |
expand, unexpand | Convert between tabs and spaces | expand(1), unexpand(1) |
fmt | Reflow paragraphs | fmt(1) |
fold | Wrap long lines | fold(1) |
pr | Paginate text for printing | pr(1) |
tsort | Order items by their dependencies | tsort(1) |
shuf | Shuffle or sample lines | shuf(1) |
ptx | Build a keyword-in-context index | ptx(1) |
Verifying Checksums and Encoding Bytes
Peios / Using Peios / Working with Text
A checksum, or digest, summarizes a file's bytes so that you can later check whether they changed. An encoding represents bytes as printable text so that they can pass through an interface that carries only text. Neither proves who produced the data: that needs a trusted source for the expected value, or a signature.
The examples use sample file names such as release.txt. Create those files
first, or substitute your own.
Record and verify digests #
Record a SHA-256 digest of a file, then check the file against it:
The check reports each file and whether its bytes still match, and fails if any doesn't. Anyone who can replace both the file and its checksum list can make the check pass, so get the expected digest through a channel you trust, or verify a signature with a trusted key.
cksum offers several algorithms through one command. Name the algorithm so
that a saved result says what it means:
The default cksum algorithm and the older sum checksum detect accidental
changes, such as transmission errors. They have too few possible values to
identify a file securely, so use a cryptographic digest such as SHA-256 for
new work.
Encode and decode bytes #
Encode a file as Base64 text, then decode it:
base32 works the same way with a different alphabet. basenc selects among
several encodings, such as --base64url, the variant used in web addresses.
Use the encoding the receiving program expects: Base64 and its URL-safe form
look alike but aren't interchangeable.
Encoding isn't encryption: anyone with the text can decode it. A decoder can write part of its output before it finds invalid input, so check its exit status, and don't let another program use the output until the whole decode has succeeded.
Commands on this page #
This page covers these commands:
| Command | Use it to | Manual |
|---|---|---|
sha256sum and the other digest commands | Record and check file digests | sha256sum(1) |
cksum | Calculate a checksum with a chosen algorithm | cksum(1) |
sum | Calculate an older checksum another system requires | sum(1) |
base64, base32 | Encode bytes as text | base64(1), base32(1) |
basenc | Encode with a chosen alphabet | basenc(1) |