fmt - Linux


Overview

fmt is a command-line utility in Linux used to format simple text by adjusting and wrapping the lines to fit a specified width. It’s primarily used to improve the readability of text files or output in the terminal, especially ideal for formatting emails or text files before further processing.

Syntax

The basic syntax of the fmt command is:

fmt [options] [file...]

If no file is specified, or if the file is -, fmt reads from standard input.

Options/Flags

  • -w WIDTH, --width=WIDTH
    Set the maximum line width (default is 75). WIDTH must be a positive integer. For instance, fmt -w 100 file.txt formats the text with each line not exceeding 100 characters.

  • -c, --crown-margin
    Preserve indentation of the first two lines, and align the rest accordingly. Useful for formatted mail responses.

  • -s, --split-only
    Split long lines, but do not join short lines. This flag maintains the intentional breaks in the original text.

  • -u, --uniform-spacing
    Reduce multiple spaces between words to one single space, and set one space between sentences.

  • -t, --tagged-paragraph
    Indentation defines paragraphs. Lines with identical indentation are considered part of the same paragraph.

  • -p PREFIX, --prefix=PREFIX
    Only format lines beginning with PREFIX, which remains intact; this is often used with bullet lists or numbered items.

Examples

  • Simple Formatting
    Format a file to a default width of 75 characters:

    fmt myfile.txt
    
  • Custom Width
    Set custom line width to 50 characters:

    fmt -w 50 myfile.txt
    
  • Formatting with Indent Preservation
    Format text with preserved indentations of paragraphs:

    fmt -c -p "> " email.txt
    

Common Issues

  • Word Splitting: Occasionally, fmt may unexpectedly split a word between lines. This typically happens with very long words that exceed the set width. To prevent this, adjust the line width appropriately.

  • Non-uniform Whitespace: Users often overlook that fmt can reformat whitespace. Use -u to ensure consistent spacing.

Integration

fmt can be easily combined with other tools in a pipeline to extend its functionality. For instance, integrating with mail for email formatting:

cat draft.txt | fmt | mail -s "Subject" someone@example.com

Or, use fmt with sed for pre-formatting modifications:

sed 's/^/> /' responses.txt | fmt -w 70 -p "> " | mail -s "Replied" user@example.com
  • fold: Breaks lines that exceed a specified width.
  • pr: Converts text files for printing, offering more detailed formatting options.
  • awk, sed: Text processing tools that can complement the functionality of fmt by manipulation before or after formatting.

For more details and updates, consult the fmt man page by running man fmt. This can provide additional insights into less common, advanced options and scenarios.