Linux fold command tutorial for beginners (with examples)
While working on the command line in Linux, one thing that you'd have probably missed is how the output gets displayed in terminal. I mean, the way it fits the available area. Have you ever found yourself stuck in a situation where-in the requirement was to make sure the output of a command fits a particular width?
If your answer is yes and/or you want to know how to do that, you'll be glad to know that in this tutorial, we will discuss a command - dubbed fold - that can help you achieve what you want. But before we do that, it's worth mentioning that all examples and instructions mentioned here have been tested on Ubuntu 16.04LTS.
Linux fold command
The fold command wraps each input line to fit in specified width. Here's the syntax of this command:
fold [OPTION]... [FILE]...
And here's how the man page describes the tool:
Wrap input lines in each FILE, writing to standard output.
Following are some Q&A-styled examples that will give you a good idea about how fold works.
Q1. How to wrap output using fold command?
By default, when you display contents of a file using cat, the output displayed covers whole width of the screen. To limit the occupied width to 80 columns, use the fold command instead.
Here's a screenshot that compares the cat command output with the output produced by fold.
Q2. How to customize number of columns in output?
By default, the fold command limits the number of columns to 80. However, you can tweak this value using the -w command line option.
fold -w[n] [file-name]
For example, the following screenshot shows how you can limit the output to 20 columns:
Q3. How to make fold break at spaces?
If you take a closer look at the screenshot in the previous section, you'll see that the output is displayed in such a way that some of the words are broken between lines. To make sure that lines only break at spaces, use the -s command line option.
fold -w[n] -s [file-name]
Here's an example:
Q4. How to make fold count bytes (not columns)?
If you want fold to count bytes instead of columns, use the -b command line option instead.
fold -b [n]
For example, the following command will break lines at 10 bytes.
fold -b 10
Quite clearly, the fold command doesn't offer a plethora of features. However, it does what is promises. The best part is that it's very easy to understand and use. We've discussed all major options the tool provides, so just practice these, and you should be ready to use fold in your day to day activities. To access the command's man page, head here.