|

Linux CLI 48 🐧 nl, fold and fmt commands

nl filename.txt
nl -n rz filename.txt
nl -n ln filename.txt
nl -n rn filename.txt
nl -i 2 filename.txt

fold longtext.txt
fold -w20 longtext.txt
fold -s  longtext.txt

cat format.txt
fmt format.txt
fmt -w20 format.txt
fmt -w20 -c format.txt

nl, fold, and fmt are three small but useful text-formatting tools. nl numbers lines; fold breaks long lines at a fixed width; fmt reflows paragraphs to a target width. They’re the kind of commands you reach for when you need to make raw text readable — for reports, citations, or terminal output.

Key point: fold and fmt both wrap text, but differently. fold is a hard wrap — it breaks at exactly the width you give, no matter what. fmt is a soft wrap — it reflows whole paragraphs, moving words to fit the width naturally. Use fold for code or unbreakable strings; use fmt for prose.


a – nl command

nl is used to number lines of text. It’s useful when referencing or citing specific lines in a document. It’s like cat -n but with more control over formatting.

Syntax:

nl [options] [file...]

Common options:

OptionPurpose
-b aNumber all lines (default)
-b tNumber only non-blank lines
-b nNumber no lines
-n lnLeft-aligned numbers
-n rnRight-aligned numbers (default)
-n rzRight-aligned, zero-padded
-i NIncrement by N (default 1)
-s STRUse STR as the separator (default TAB)
-w NUse N columns for the number
-v NStart numbering at N

Examples:

# Look at the file
$ cat filename.txt
first line
second line
third line
fourth line

# Default numbering — right-aligned, tab separator
$ nl filename.txt
     1	first line
     2	second line
     3	third line
     4	fourth line

# Zero-padded numbers
$ nl -n rz filename.txt
000001	first line
000002	second line
000003	third line
000004	fourth line

# Left-aligned numbers
$ nl -n ln filename.txt
1     	first line
2     	second line
3     	third line
4     	fourth line

# Right-aligned (explicit)
$ nl -n rn filename.txt
     1	first line
     2	second line
     3	third line
     4	fourth line

# Increment by 2
$ nl -i 2 filename.txt
     1	first line
     3	second line
     5	third line
     7	fourth line

# Skip blank lines
$ cat mixed.txt
first

second

third

$ nl -b t mixed.txt
     1	first

     2	second

     3	third

Comparing nl formats:

FlagExample output
-n ln1 \tfirst line
-n rn1\tfirst line
-n rz000001\tfirst line

More examples:

# Use a custom separator
$ nl -s ': ' filename.txt
     1: first line
     2: second line
     3: third line
     4: fourth line

# Wider number column
$ nl -w 4 filename.txt
   1	first line
   2	second line
   3	third line
   4	fourth line

# Start numbering at 100
$ nl -v 100 filename.txt
   100	first line
   101	second line
   102	third line
   103	fourth line

# Number all lines, zero-padded, custom separator
$ nl -b a -n rz -s ': ' filename.txt
000001: first line
000002: second line
000003: third line
000004: fourth line

Tip: nl is often used with sed or awk for numbering, but nl is simpler and faster when you just want line numbers. For plain numbering, nl is the dedicated tool.


b – fold command

fold wraps input text into a specified width. It’s useful for formatting long lines of text into readable chunks — particularly when you have a long string that needs to fit a terminal or a fixed-width column.

Syntax:

fold [options] [file...]

Common options:

OptionPurpose
-w NWrap at N columns (default 80)
-sBreak at spaces instead of mid-word
-bCount bytes instead of columns
-cCount characters (respects multibyte)

Examples:

# Look at the long line
$ cat longtext.txt
This is a very long line of text that will not fit on a single terminal line and needs to be wrapped.

# Default wrap (80 columns)
$ fold longtext.txt
This is a very long line of text that will not fit on a single terminal line a
nd needs to be wrapped.

# Wrap at 20 columns
$ fold -w20 longtext.txt
This is a very long 
line of text that wi
ll not fit on a sing
le terminal line and
 needs to be wrapped
.

# Wrap at 20 columns, breaking at spaces
$ fold -s -w20 longtext.txt
This is a very long 
line of text that 
will not fit on a 
single terminal 
line and needs to 
be wrapped.

fold vs fold -s:

Without -s (breaks mid-word):
This is a very long
line of text that wi
ll not fit on a sing
le terminal line

With -s (breaks at spaces):
This is a very long
line of text that
will not fit on a
single terminal line

More examples:

# Wrap a long line at exactly 40 characters
$ echo "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJ" | fold -w40
abcdefghijklmnopqrstuvwxyz0123456789ABCDEF
GHIJ

# Fold a file at 60 columns
$ fold -w60 document.txt

# Fold with space-breaking
$ fold -s -w60 document.txt

# Fold code (break at exact width — no word awareness)
$ fold -w72 script.py

# Fold binary data (byte counting)
$ fold -b -w40 data.bin

# Fold with multibyte characters
$ echo "café résumé naïve" | fold -c -w10

When to use fold:

  • Wrapping code or URLs where mid-token breaks are acceptable
  • Fitting text into a fixed-width column
  • Wrapping text where you control the width exactly
  • Handling text that isn’t natural-language prose

Note: fold doesn’t understand paragraphs. It processes each line independently and doesn’t reflow across line boundaries. For paragraphs, use fmt.


c – fmt command

fmt formats text paragraphs. It automatically adjusts the length of lines to fit within width margins. The default length is 75 characters. Unlike fold, fmt reflows entire paragraphs — it moves words around to make lines fit naturally.

Syntax:

fmt [options] [file...]

Common options:

OptionPurpose
-w NSet line width to N (default 75)
-cCrown margin mode — consistent paragraph width, break at natural stopping points
-sSplit long lines but don’t join short ones
-uUniform spacing (one space between words, two after sentences)
-p PREFIXOnly reformat lines starting with PREFIX
-tTagged paragraph mode

Examples:

# Look at the unformatted text
$ cat format.txt
This is a paragraph of text that is written on one very long line without any consideration for width or readability. It just keeps going and going.

# Default formatting (75 columns)
$ fmt format.txt
This is a paragraph of text that is written on one very long line without
any consideration for width or readability. It just keeps going and going.

# Format at 20 columns
$ fmt -w20 format.txt
This is a paragraph
of text that is
written on one very
long line without
any consideration
for width or
readability. It
just keeps going and
going.

# Format at 20 columns with crown mode
$ fmt -w20 -c format.txt
This is a
paragraph of text
that is written on
one very long line
without any
consideration for
width or
readability. It
just keeps going
and going.

How fmt differs from fold:

Aspectfoldfmt
Break pointsExactly at widthAt word boundaries
ParagraphsLine-by-lineReflows whole paragraphs
Joining linesNoYes — joins short lines
Best forCode, URLsProse, documents

fmt reflows — fold doesn’t:

Input (two short lines):
The quick brown fox
jumps over the lazy dog.

fold -w80 (unchanged):
The quick brown fox
jumps over the lazy dog.

fmt -w80 (reflowed):
The quick brown fox jumps over the lazy dog.

More examples:

# Reformat a file to 60 columns
$ fmt -w60 document.txt

# Format with crown mode (consistent paragraph width)
$ fmt -w60 -c document.txt

# Split long lines but don't join short ones
$ fmt -s document.txt

# Uniform spacing
$ fmt -u document.txt

# Format only lines starting with "> " (quoted text)
$ fmt -p '> ' email.txt

# Format a paragraph from stdin
$ echo "This is a long sentence that should be reformatted to fit within a narrower margin for readability." | fmt -w30
This is a long sentence
that should be reformatted
to fit within a narrower
margin for readability.

Default width of fmt:

# Default is 75 characters
$ fmt format.txt
This is a paragraph of text that is written on one very long line without
any consideration for width or readability. It just keeps going and going.
#                                                                         ^
#                                                              75 columns |

More on crown mode (-c):

Without -c, fmt may produce slightly different line lengths, especially for the last line of each paragraph. With -c, it tries to make all lines consistent and break at a more natural stopping point.

$ fmt -w20 format.txt
This is a paragraph
of text that is
written on one very
long line without
any consideration
for width or
readability. It
just keeps going and
going.

$ fmt -w20 -c format.txt
This is a
paragraph of text
that is written on
one very long line
without any
consideration for
width or
readability. It
just keeps going
and going.

Tip: Use fmt for README files, plain-text documentation, or when you want to reflow prose to a specific width. It’s especially useful after editing a document with a text editor that produces uneven line lengths.


Complete Example Session

# ============================================
# PART 1: NL — NUMBER LINES
# ============================================

$ cat filename.txt
first line
second line
third line
fourth line

$ nl filename.txt
     1	first line
     2	second line
     3	third line
     4	fourth line

$ nl -n rz filename.txt
000001	first line
000002	second line
000003	third line
000004	fourth line

$ nl -n ln filename.txt
1     	first line
2     	second line
3     	third line
4     	fourth line

$ nl -n rn filename.txt
     1	first line
     2	second line
     3	third line
     4	fourth line

$ nl -i 2 filename.txt
     1	first line
     3	second line
     5	third line
     7	fourth line

# ============================================
# PART 2: NL — SKIP BLANK LINES
# ============================================

$ cat mixed.txt
first

second

third

$ nl -b t mixed.txt
     1	first

     2	second

     3	third

# ============================================
# PART 3: NL — CUSTOM SEPARATOR
# ============================================

$ nl -s ': ' filename.txt
     1: first line
     2: second line
     3: third line
     4: fourth line

$ nl -b a -n rz -s ': ' filename.txt
000001: first line
000002: second line
000003: third line
000004: fourth line

# ============================================
# PART 4: FOLD — WRAP AT FIXED WIDTH
# ============================================

$ cat longtext.txt
This is a very long line of text that will not fit on a single terminal line and needs to be wrapped.

$ fold longtext.txt
This is a very long line of text that will not fit on a single terminal line a
nd needs to be wrapped.

$ fold -w20 longtext.txt
This is a very long 
line of text that wi
ll not fit on a sing
le terminal line and
 needs to be wrapped
.

# ============================================
# PART 5: FOLD — BREAK AT SPACES
# ============================================

$ fold -s -w20 longtext.txt
This is a very long 
line of text that 
will not fit on a 
single terminal 
line and needs to 
be wrapped.

# ============================================
# PART 6: FMT — REFLOW PARAGRAPHS
# ============================================

$ cat format.txt
This is a paragraph of text that is written on one very long line without any consideration for width or readability. It just keeps going and going.

$ fmt format.txt
This is a paragraph of text that is written on one very long line without
any consideration for width or readability. It just keeps going and going.

$ fmt -w20 format.txt
This is a paragraph
of text that is
written on one very
long line without
any consideration
for width or
readability. It
just keeps going and
going.

$ fmt -w20 -c format.txt
This is a
paragraph of text
that is written on
one very long line
without any
consideration for
width or
readability. It
just keeps going
and going.

# ============================================
# PART 7: FMT VS FOLD
# ============================================

# Two short lines
$ printf "The quick brown fox\njumps over the lazy dog.\n"

# fold — leaves them alone
$ printf "The quick brown fox\njumps over the lazy dog.\n" | fold -w80
The quick brown fox
jumps over the lazy dog.

# fmt — joins them
$ printf "The quick brown fox\njumps over the lazy dog.\n" | fmt -w80
The quick brown fox jumps over the lazy dog.

# ============================================
# PART 8: COMBINING NL, FOLD, FMT
# ============================================

# Number the reflowed output
$ fmt -w40 document.txt | nl

# Wrap a long line and number it
$ fold -s -w30 longtext.txt | nl -n rz

# Reflow a file and save it
$ fmt -w72 messy.txt > clean.txt

# Number non-blank lines of a reflowed file
$ fmt -w60 document.txt | nl -b t

# ============================================
# PART 9: REAL-WORLD USES
# ============================================

# Number lines of source code for a code review
$ nl -b a -n rz script.sh | head -20
000001	#!/bin/bash
000002	
000003	# A simple script
...

# Wrap a long URL list
$ fold -w80 urls.txt

# Reflow a plain-text README to 72 columns
$ fmt -w72 README.txt > README.formatted.txt

# Number lines of a log after filtering
$ grep ERROR app.log | nl -n rz
000001	2024-01-15 ERROR: connection refused
000002	2024-01-15 ERROR: timeout
000003	2024-01-15 ERROR: disk full

Quick Reference

nl

CommandPurpose
nl FILENumber all lines (right-aligned)
nl -b a FILENumber all lines
nl -b t FILENumber non-blank lines
nl -n ln FILELeft-aligned numbers
nl -n rn FILERight-aligned numbers
nl -n rz FILEZero-padded numbers
nl -i N FILEIncrement by N
nl -s STR FILECustom separator
nl -w N FILENumber column width
nl -v N FILEStart at N

fold

CommandPurpose
fold FILEWrap at 80 columns
fold -w N FILEWrap at N columns
fold -s FILEBreak at spaces
fold -s -w N FILEBoth
fold -b FILECount bytes
fold -c FILECount characters

fmt

CommandPurpose
fmt FILEReflow at 75 columns
fmt -w N FILEReflow at N columns
fmt -c FILECrown mode (consistent width)
fmt -s FILESplit only, don’t join
fmt -u FILEUniform spacing
fmt -p PREFIX FILEOnly lines with prefix

Tool Comparison

ToolPurposeWraps atReflows?
nlNumber lines
foldHard-wrap linesExact widthNo
fmtReflow paragraphsWord boundariesYes
cat -nNumber lines

Default Widths

ToolDefault
fold80 columns
fmt75 columns

Best Practices

Do This:

# Use nl for line numbers in reviews
nl -b a -n rz script.sh              # ✅

# Use fold -s to avoid mid-word breaks
fold -s -w72 document.txt            # ✅

# Use fmt for prose
fmt -w72 README.txt                  # ✅

# Use fmt -c for consistent paragraph width
fmt -w72 -c document.txt             # ✅

# Combine nl with other tools
grep ERROR app.log | nl              # ✅

# Save formatted output
fmt -w72 messy.txt > clean.txt       # ✅

# Use fold for code/URLs
fold -w80 urls.txt                   # ✅

Don’t Do This:

# Don't use fold for prose — it breaks mid-word
fold -w72 article.txt                # ❌ use fmt instead

# Don't use fmt for code — it reflows
fmt -w72 script.py                   # ❌ use fold

# Don't forget -s with fold
fold -w20 text.txt                   # ❌ breaks mid-word

# Don't use nl when cat -n is enough
nl -b a file.txt                     # ⚠️  cat -n is simpler

# Don't expect fold to join lines
fold -w80 short-lines.txt            # ❌ use fmt

# Don't forget the default width
fmt document.txt                     # ⚠️  75, not 80

Common Pitfalls

PitfallProblemSolution
fold breaks mid-wordUgly outputAdd -s
fmt joins lines unexpectedlyLost structureUse fold
nl shows blank linesNumbering allUse -b t
Wrong number formatMisalignedUse -n rn / -n rz
Default width wrongToo narrow/wideSet -w N
fmt on codeReflows codeUse fold
Tabs in outputConfusing alignmentUse -s ' '
fold on UTF-8Byte splittingUse -c

Real-World Examples

1. Number Lines for Code Review

$ nl -b a -n rz script.sh | head -10
000001	#!/bin/bash
000002	
000003	# Script to back up files
000004	
000005	SRC="/home/kronos"
000006	DST="/backup"
000007	
000008	rsync -av --delete "$SRC" "$DST"
000009	
000010	echo "Backup complete"

2. Number Non-Blank Lines

$ nl -b t document.txt
     1	Chapter 1

     2	Introduction

     3	This is the first paragraph.

3. Zero-Padded Numbering

$ nl -n rz file.txt
000001	line one
000002	line two
000003	line three

4. Wrap a Long URL

$ echo "https://example.com/very/long/path/to/a/resource/that/needs/wrapping" | fold -w40
https://example.com/very/long/path/to/a/
resource/that/needs/wrapping

5. Wrap at Spaces

$ echo "The quick brown fox jumps over the lazy dog" | fold -s -w20
The quick brown fox
jumps over the lazy
dog

6. Reflow a Paragraph

$ cat messy.txt
This   is  a paragraph
with   uneven   spacing
and   broken   lines.

$ fmt -w40 messy.txt
This is a paragraph with uneven
spacing and broken lines.

7. Reflow at 60 Columns

$ fmt -w60 article.txt > article.formatted.txt

8. Reflow with Crown Mode

$ fmt -w60 -c document.txt

9. Format Quoted Text in an Email

$ fmt -p '> ' email.txt

10. Combine fmt and nl

$ fmt -w60 document.txt | nl -b t
     1	This is the first line of the reflowed text
     2	which now fits nicely within sixty columns
     3	instead of running off the edge.

11. Number Log Errors

$ grep ERROR app.log | nl -n rz
000001	2024-01-15 ERROR: connection refused
000002	2024-01-15 ERROR: timeout
000003	2024-01-15 ERROR: disk full

12. Prepare Text for a Fixed-Width Display

$ fold -w32 -s menu.txt

13. Number and Wrap a File

$ fold -s -w40 longtext.txt | nl -n rz
000001	This is a very long line of text
000002	that will not fit on a single
000003	terminal line and needs to be
000004	wrapped.

14. Fix a File with Long Lines

$ fmt -w72 longlines.txt > fixed.txt

15. Check the Default Width

$ echo "The default width is 75 characters for fmt and 80 for fold. This line is designed to be long enough to see where the break happens." | fmt
The default width is 75 characters for fmt and 80 for fold. This line is
designed to be long enough to see where the break happens.

16. Format a Man Page Source

$ fmt -w72 mytool.1 > mytool.1.formatted

17. Add Line Numbers to diff Output

$ diff -u old.txt new.txt | nl
     1	--- old.txt
     2	+++ new.txt
     3	@@ -1,3 +1,3 @@
     4	 line one
     5	-old line two
     6	+new line two
     7	 line three

18. Reflow README to 72 Columns

$ fmt -w72 README.md > README.formatted.md

Visual: nl, fold, fmt

┌──────────────────────────────────────────────┐
│                  nl                          │
│                                              │
│  Input:          Output:                     │
│  first line      1    first line             │
│  second line     2    second line            │
│  third line      3    third line             │
│                                              │
│  Adds line numbers                           │
│                                              │
└──────────────────────────────────────────────┘

┌──────────────────────────────────────────────┐
│                 fold -w20                    │
│                                              │
│  Input:                                      │
│  This is a very long line of text            │
│                                              │
│  Output:                                     │
│  This is a very long  ← exactly 20 chars     │
│  line of text         ← exactly 20 chars     │
│                                              │
│  Hard break at exact width                   │
│                                              │
└──────────────────────────────────────────────┘

┌──────────────────────────────────────────────┐
│                 fmt -w20                     │
│                                              │
│  Input:                                      │
│  This is a very long line of text            │
│                                              │
│  Output:                                     │
│  This is a very long  ← 20 chars             │
│  line of text         ← reflowed             │
│                                              │
│  Soft break at word boundaries,              │
│  reflows whole paragraphs                    │
│                                              │
└──────────────────────────────────────────────┘

Summary

CommandPurposeExample
nl FILENumber all linesnl filename.txt
nl -b a FILENumber all linesnl -b a filename.txt
nl -b t FILENumber non-blanknl -b t filename.txt
nl -n ln FILELeft-alignednl -n ln filename.txt
nl -n rn FILERight-alignednl -n rn filename.txt
nl -n rz FILEZero-paddednl -n rz filename.txt
nl -i N FILEIncrement by Nnl -i 2 filename.txt
nl -s STR FILECustom separatornl -s ': ' filename.txt
fold FILEWrap at 80fold longtext.txt
fold -w N FILEWrap at Nfold -w20 longtext.txt
fold -s FILEBreak at spacesfold -s longtext.txt
fold -s -w N FILEBothfold -s -w20 longtext.txt
fmt FILEReflow at 75fmt format.txt
fmt -w N FILEReflow at Nfmt -w20 format.txt
fmt -c FILECrown modefmt -w20 -c format.txt
fmt -s FILESplit onlyfmt -s format.txt
fmt -u FILEUniform spacingfmt -u format.txt
fmt -p P FXPrefix modefmt -p '> ' email.txt

Key takeaways:

  • nl numbers lines — use -b t for non-blank only, -n rz for zero-padded, -i N for increments
  • fold does a hard wrap at an exact column width — use -s to break at spaces
  • fmt does a soft wrap — it reflows whole paragraphs at word boundaries
  • fold is for code, URLs, and fixed-width output; fmt is for prose
  • The default width is 80 for fold and 75 for fmt
  • fmt -c (crown mode) produces more consistent paragraph widths
  • fmt -s splits long lines without joining short ones
  • fmt -p PREFIX reformats only lines starting with a prefix (great for quoted email)
  • Combine them: fmt -w60 document.txt | nl -b t — reflow then number
  • Use nl instead of cat -n when you need format control

Remember: nl numbers, fold wraps hard, fmt reflows soft. If you’re formatting prose — READMEs, documentation, email — use fmt. If you’re formatting code, URLs, or fixed-width output — use fold. And when you need line numbers for a review or a report, nl gives you the control that cat -n doesn’t. These three are small tools, but they turn raw text into something readable.


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!