How to wrap each input line to fit in specified width in Linux?

The fold command in Linux is used to wrap each input line to fit within a specified width. This utility makes files with long lines more readable on terminals with limited screen width, as most Linux/Unix terminals default to 80 columns. When reading files with long lines, content can extend beyond the screen width, making it difficult to read without horizontal scrolling.

The fold command allows users to set the maximum length of a line and performs automatic line wrapping. It was included in the first version of POSIX and remains a standard tool across Unix-like systems.

Syntax

The general syntax of the fold command is −

fold [OPTION]... [FILE]...

Options

Option Description
-b, --bytes Count bytes instead of columns
-c, --characters Count characters instead of columns
-s, --spaces Break at word boundaries (spaces) instead of exact character count
-w, --width=WIDTH Use WIDTH columns instead of the default 80
--help Display help information and exit
--version Output version information and exit

Examples

Basic Usage with Default Width

By default, fold wraps lines at 80 columns −

$ cat text.txt
You can decide what you are going to think in any given situation. Your thoughts and feelings determine your actions and determine the results you get. It all starts with your thoughts.

$ fold text.txt
You can decide what you are going to think in any given situation. Your thoughts
 and feelings determine your actions and determine the results you get. It all s
tarts with your thoughts.

Specifying Custom Width

To wrap lines at a specific width, use the -w option −

$ cat text.txt
Hey, welcome to tutorialspoint...

$ fold -w10 text.txt
Hey, welco
me to tuto
rialspoint
...

Breaking at Word Boundaries

The -s option ensures lines break at spaces rather than mid-word −

$ echo "This is a long line that needs to be wrapped properly" | fold -w20 -s
This is a long line
that needs to be
wrapped properly

Reading from Standard Input

Fold can process input directly from the terminal −

$ fold -w15
Hey, welcome to Tutorialspoint and enjoy learning Linux commands
Hey, welcome to
 Tutorialspoin
t and enjoy le
arning Linux c
ommands

Key Points

  • Default width is 80 columns if not specified with -w

  • Without -s, fold breaks lines at exact character positions, potentially splitting words

  • The -s option makes output more readable by preserving word integrity

  • Fold works with both files and standard input

Conclusion

The fold command is an essential Linux utility for formatting text to fit specific display widths. It provides flexible options for counting methods and word-boundary preservation, making it valuable for text processing and improving readability on various terminal sizes.

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

801 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements