Skip to content

fold Command: Wrap Text to Fit a Specified Width

Summary

The fold command is a simple utility that wraps lines of text to a specified width. This is useful for displaying long lines in terminals or text editors with limited width, or for preparing text for systems with specific line length requirements.

Introduction

The fold command takes text from standard input or specified files and breaks lines that exceed a given width. By default, it breaks lines at 80 characters, but this can be adjusted using the -w option. This command is particularly helpful when dealing with text files that contain very long lines, making them difficult to read or process in environments with limited screen space or processing constraints.

Use Case and Examples

Basic Usage: Folding to Default Width (80 characters)

fold long_text_file.txt
This command reads the file long_text_file.txt and outputs its content, wrapping lines exceeding 80 characters to the next line.

Folding to a Specific Width (e.g., 40 characters)

fold -w 40 long_text_file.txt
This command reads the file long_text_file.txt and wraps lines exceeding 40 characters.

Folding from Standard Input

cat long_text_file.txt | fold -w 60
This pipes the contents of long_text_file.txt to the fold command, which wraps lines to 60 characters before displaying them on the terminal.

Breaking Lines at Word Boundaries

fold -s -w 30 long_text_file.txt
This command reads long_text_file.txt and wraps lines to 30 characters, attempting to break lines at whitespace characters to avoid splitting words. The -s flag ensures that breaks occur at spaces.

Folding Without Breaking Words

fold -w 20 <<< "This is a verylongwordthatneedstobefolded"
This command uses a "here string" to provide the input to fold. The output will break the long word into segments based on the specified width (20 characters).

Commonly used flags

Flag Description Example
-w, --width=WIDTH Specifies the maximum line width. fold -w 50 file.txt
-s, --spaces Breaks lines at whitespace characters. fold -s -w 60 file.txt
-b, --bytes Count using bytes rather than columns. This is important when dealing with multibyte character sets. fold -b -w 10 file_with_utf8_chars.txt
-n, --no-break If a width parameter is given, folding still happens, but spaces aren't considered a breaking point. fold -n -w 10 file_with_spaces.txt


Share on Share on

Comments