Peios Learn
Documentation

Peios

Peios Peios Kernel Universal Directory Project

Developer Tools

Trail Acta Provium clackatoo CAF GCSL Pekit

Applications

Framewright

Standards and Conventions

Standards and Conventions Peios Specifications
Peios

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:

sort counts.txt > sorted-counts.txt

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 sort names.txt

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 opening.txt details.txt > report.txt

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:

head -n 2 names.txt

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:

od -An -tx1 sample.bin

-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:

cut -d : -f 1 counts.txt

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.txt puts 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.txt combines 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. comm compares 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:

split -l 2 original.txt piece-

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:

CommandUse it toManual
catWrite files to output in ordercat(1)
moreRead a file one screen at a timemore(1)
nlNumber linesnl(1)
tacPrint lines in reverse ordertac(1)
head, tailRead the start or end of a filehead(1), tail(1)
odShow bytes as numbersod(1)
cutSelect fields from each linecut(1)
pasteCombine lines by positionpaste(1)
joinCombine lines by a shared keyjoin(1)
commCompare two sorted filescomm(1)
split, csplitSplit a file into piecessplit(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 sort -n counts.txt

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 sort names.txt | uniq -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:

printf 'aster birch\n' | LC_ALL=C tr 'a-z' 'A-Z'

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:

printf 'prepare build\nbuild test\n' | tsort

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:

CommandUse it toManual
sortSort linessort(1)
uniqCollapse or count repeated neighboring linesuniq(1)
wcCount lines, words, and byteswc(1)
trTranslate or delete characterstr(1)
expand, unexpandConvert between tabs and spacesexpand(1), unexpand(1)
fmtReflow paragraphsfmt(1)
foldWrap long linesfold(1)
prPaginate text for printingpr(1)
tsortOrder items by their dependenciestsort(1)
shufShuffle or sample linesshuf(1)
ptxBuild a keyword-in-context indexptx(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:

sha256sum release.txt > checksums.txt
sha256sum -c checksums.txt

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:

cksum -a sha256 release.txt

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:

base64 original.bin > encoded.txt
base64 -d encoded.txt > decoded.bin

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:

CommandUse it toManual
sha256sum and the other digest commandsRecord and check file digestssha256sum(1)
cksumCalculate a checksum with a chosen algorithmcksum(1)
sumCalculate an older checksum another system requiressum(1)
base64, base32Encode bytes as textbase64(1), base32(1)
basencEncode with a chosen alphabetbasenc(1)

Peios Learn — documentation for Peios software.

Built with Trail.