How to format contents of a text file in the Linux system?

Sometimes text files are not well formatted for presentation. While manual formatting works for small files, it becomes impractical for large files. In Linux, we use the fmt command to format the contents of text files efficiently.

The fmt command is used to format, simplify, and optimize text files in the Linux system. If no file is specified, fmt reads input from standard input. By default, it creates text lines that are 75 characters wide.

Syntax

The general syntax of the fmt command is as follows −

fmt [-WIDTH] [OPTION]... [FILE]...

Options

Brief description of options available in the fmt command:

Sr.No. Option & Description
1 -c, --crown-margin
Preserve the indentation of the first two lines
2 -p, --prefix=STRING
Reformat beginning lines with specified STRING, reattaching the prefix to reformatted lines
3 -s, --split-only
Split only long lines, but don't refill
4 -t, --tagged-paragraph
Indentation of first-line different from second
5 -u, --uniform-spacing
One space between words, two after sentences
6 -w, --width=WIDTH
Maximum line width (default of 75 columns)
7 -g, --goal=WIDTH
Goal width (default of 93% of width)
8 --help
Displays a help message and then exits
9 --version
It gives info about the version and then exits

Examples

Formatting Text from Standard Input

Here, we will format text from standard input instead of a file using the fmt command:

$ fmt
Hey,
welcome
to
Tutorialspoint...
Hey, welcome to Tutorialspoint...

Formatting Text from a File

First, create a file with unformatted text using the cat command:

$ cat >text.txt
Hey,
welcome
to
Tutorialspoint...
^C

Then format the contents of the file using the fmt command:

$ fmt text.txt
Hey, welcome to Tutorialspoint...

Setting Custom Width

Format text with a specific line width (e.g., 50 characters):

$ fmt -w 50 text.txt

Using Crown Margin

Preserve indentation of the first two lines:

$ fmt -c text.txt

Getting Help and Version Information

To check more information about the fmt command, use the --help option:

$ fmt --help

To check version information of the fmt command:

$ fmt --version

Conclusion

The fmt command is a powerful tool for formatting text files in Linux by adjusting line widths and spacing. It's particularly useful for preparing text documents for display or printing, making unformatted text more readable and professionally presented.

Updated on: 2026-03-17T09:01:38+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements