How to Wrap Long Lines of Text Using the fold Command in Linux

When you dump a raw block of text from an unformatted database directly into a Linux terminal, the text often renders as one massive, continuous string of characters. If a single line of text is 4,000 characters long, it will brutally smash into the right edge of your terminal window and abruptly wrap around to the next line in the exact middle of a word, rendering the output completely illegible. To mathematically force the Linux kernel to cleanly wrap massive lines of text at specific, hard-coded character widths, you must use the fold command.

How the fold Command Works

The fold command is a structural formatting engine. It reads the raw data streaming into it, counts the exact number of characters (bytes), and violently injects a hard line break (a newline character) the exact millisecond it hits your designated width limit.

By default, if you execute the command without any specific instructions, fold assumes a standard terminal width and will automatically break every line exactly at the 80th character.

fold unformatted_data.txt

Setting Custom Width Limits

If you are preparing a text file to be printed on a specific physical label, or imported into a strict database schema that only accepts 50-character strings, the default 80-character limit is useless. You must override the default using the -w (width) flag.

To force the text to wrap at exactly 50 characters, type:

fold -w 50 unformatted_data.txt

The engine will now flawlessly execute a hard line break precisely at character 50, character 100, character 150, and so on.

Wrapping at Clean Word Boundaries

The standard fold command is mathematically aggressive; it does not care about human language. If character 50 happens to fall directly inside the word “Server”, the command will violently chop the word in half, putting “Ser” on line one and “ver” on line two. This makes reading text incredibly annoying.

To force the fold engine to respect standard human linguistics, you must append the -s (spaces) flag.

fold -w 50 -s unformatted_data.txt

The -s flag completely alters the mathematical logic. When the engine approaches the 50-character limit, it looks backwards for the nearest standard Space character. Instead of chopping a word in half, it cleanly executes the line break precisely at the space, ensuring that every single word remains mathematically intact and visually legible.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.