Skip to main content

The `fold` Command in Linux

The fold command in Linux is used to wrap the input text to fit a specified width.

This is particularly useful when dealing with long lines of text that extend beyond the viewable area of a terminal or when formatting text to be sent to devices with a fixed width, like printers.


The basic syntax of the fold command is as follows:

fold [OPTIONS]... [FILE]...

When no FILE, or when FILE is -, the command reads standard input.


Below is a table summarizing the most common options available with fold:

--width-wWrap lines at WIDTH columns (default is 80).
--bytes-bCount bytes rather than columns (ignores line spacing).
--spaces-sBreak at spaces (wraps lines at word boundaries).

Creating a Sample Text File with vim

To create a sample file to work with the fold command, we can use vim. Open the terminal and type:

vim longtext.txt

Press i to enter insert mode and copy or type the following long line of text:

This is a very long line of text that is meant to be an example to demonstrate how the fold command works in a Linux environment. By using fold, we can adjust the width of the text so that it wraps and fits nicely into a specified width.

To save and exit vim, press Esc, type :wq, and hit Enter.

Examples of Using fold

Example 1: Basic Wrapping

To wrap the text at the default width (80 columns):

fold longtext.txt

This will output the text with each line wrapped at 80 columns.

Example 2: Custom Width

To wrap lines to a width of 40 columns:

fold -w 40 longtext.txt

This changes the wrap width to 40 columns.

Example 3: Wrap at Word Boundaries

To avoid breaking words, use the -s option:

fold -s -w 40 longtext.txt

This wraps lines at the last space before the 40-column width.

Example 4: Counting Bytes Instead of Columns

If you're dealing with a file where you need to count bytes rather than columns (maybe because of multibyte characters), use:

fold -b -w 40 longtext.txt

This will count bytes, ensuring that multibyte characters are not split.

Combining fold with Other Commands

fold can be used in combination with other Unix commands through piping. For example, to view the wrapped content with less:

fold -w 40 longtext.txt | less

Or to save the wrapped version to a new file:

fold -w 40 longtext.txt > wrappedtext.txt

The fold command is an essential text processing tool in Unix-like operating systems for ensuring that output fits within a certain width. It's especially handy for formatting text on the command line, scripting, and preparing data for display on devices with strict width constraints.

What Can You Do Next 🙏😊

If you liked the article, consider subscribing to Cloudaffle, my YouTube Channel, where I keep posting in-depth tutorials and all edutainment stuff for software developers.

YouTube @cloudaffle