The fold command in Linux is used to wrap long lines of text into a specified width. Itโs especially useful when viewing logs, code, or output that runs off the screen.
๐ What is fold?
fold breaks long lines into shorter lines so they fit neatly within a given width.
๐ Great for:
- Terminal readability
- Formatting text files
- Preparing output for printing
โ Basic Syntax
fold [options] filename
๐ Basic Example
fold file.txt
๐ Wraps lines at the default width (usually 80 characters)
๐ Set Line Width
fold -w 50 file.txt
๐ Wraps lines at 50 characters
โ๏ธ Break at Spaces (Cleaner Output)
fold -s -w 50 file.txt
-sโ break at spaces (not mid-word)-wโ set width
๐ Produces more readable text
๐ Use with Piping
cat file.txt | fold -w 60
๐ Wraps output from another command
๐งช Real-World Examples
Format a long log file
fold -w 80 logfile.txt
Wrap text neatly for display
echo "This is a very long line of text..." | fold -w 40
Combine with grep
grep "error" logfile.txt | fold -w 60
๐ Makes long log entries easier to read
โ๏ธ Useful Options
| Option | Description |
|---|---|
-w | Set line width |
-s | Break at spaces |
-b | Count bytes instead of columns |
โ ๏ธ Common Mistakes
- โ Forgetting
-s(words split awkwardly) - โ Using too small width (hard to read)
- โ Confusing with text editors (this is output-only)
๐ง Pro Tips
- Use
foldwhen viewing large logs in terminal Combine with
less:fold -w 80 file.txt | less- Great for preparing text before printing
๐ Quick Summary
foldwraps long lines- Use
-wto control width - Use
-sfor clean word breaks - Works great with pipes (
|)
๐ฏ Final Thoughts
The fold command is simple but extremely useful when dealing with long lines of text. It improves readability and helps format output for both terminal viewing and printing.