fold

Wrap long lines to a specified width. Useful for terminal output, logs, and “make it readable” pipelines.

Category: Text Processing Line wrapping Formatting Pipelines coreutils

What it does

fold wraps each input line so that no line exceeds a given width. By default it breaks at a fixed column (often splitting words). With -s, it prefers breaking at whitespace when possible.

How it works (mechanical)

fold scans text left-to-right and inserts newline breaks once the current output line reaches the configured width. It does not “reflow paragraphs” like a word processor — it simply inserts hard line breaks.

  • -w N sets the wrap width (columns)
  • -s breaks at spaces/tabs when possible (word-friendly)
  • -b counts bytes rather than columns (useful with some encodings)

10 Practical Examples

# 1) Wrap to 80 columns (classic terminal width)
fold -w 80 file.txt
# 2) Wrap to 120 columns
fold -w 120 file.txt
# 3) Word-friendly wrapping (break on whitespace if possible)
fold -s -w 80 file.txt
# 4) Wrap STDOUT from a command
ip -details link show | fold -s -w 120
# 5) Wrap a single long line from a variable
printf "%s\n" "$LONG_LINE" | fold -w 80
# 6) Wrap and then number the wrapped output
some_command | fold -s -w 100 | nl -ba
# 7) Wrap a base64 string for emailing/pasting (classic use case)
base64 bigfile.bin | fold -w 76
# 8) Wrap JSON or large one-line output for quick reading (not “pretty print”)
cat one-line.json | fold -s -w 120
# 9) Wrap long grep matches to avoid horizontal scrolling
grep -R "some very long pattern" -n . | fold -s -w 140
# 10) Compare with fmt (paragraph reflow) — different tools
fmt -w 80 text.txt
fold -w 80 text.txt

Notes & Gotchas

  • Not paragraph-aware: fold inserts hard breaks; it doesn’t reflow paragraphs semantically.
  • Words can split: without -s it will split words mid-word when needed.
  • Unicode width: terminal column width and byte length can differ with multi-byte characters.
  • Good with pipes: fold is great when you just need “readable in the terminal” output.

Historical Context

fold comes from the Unix tradition of formatting tools designed for fixed-width terminals and printers. It’s still useful today for quick readability and for formatting encoded data (like base64) to conventional line lengths.

Modern Equivalent (if applicable)

For structured output (JSON, YAML, etc.), modern tools may be better: jq for JSON formatting, or application-specific formatters. But for raw “wrap this text to fit my terminal,” fold is still the simplest tool.

Related Commands

  • fmt — reflow paragraphs to a width (more “writerly”)
  • pr — paginate/format for printing
  • column — align columns in tabular output
  • nl — line numbering
  • sed, awk — programmable transforms