The fmt command is a text formatting tool that simplifies making text more readable by adjusting its layout. It takes input from either a file or standard input and formats the text by filling and joining lines to produce output within a specified width. By default, fmt wraps lines to 75 characters, which can be adjusted using command-line options. It’s particularly useful for reformatting text documents, email drafts, or any plain text file that needs uniform line lengths, ensuring a cleaner and more consistent content presentation.
In this tutorial, we will discuss the basics of fmt and some of its main features. All commands and instructions mentioned here have been tested on Ubuntu 24.04.
Linux fmt command
The fmt command is a simple text formatting tool available to users of the Linux command line. Following is its basic syntax:
fmt [-WIDTH] [OPTION]... [FILE]...
And here’s how the man page describes it:
Reformat each paragraph in the FILE(s), writing to standard output. The option -WIDTH is an abbreviated form of --width=DIGITS.
The following are some Q&A-style examples that should give you a good idea of fmt’s usage.
Q1. How to format contents of file in single line using fmt?
When used in its basic form (without options), the fmt command does this. You only need to pass the filename as an argument.
fmt [file-name]
The following screenshot shows the command in action:
So you can see that multiple lines in the file were formatted in a way that everything got clubbed up in a single line. Please note that the original file (file1 in this case) remains unaffected.
Q2. How to change the maximum line width?
By default, the maximum width of a line that fmt command produces in output is 75. However, if you want, you can change that using the -w command line option, which requires a numerical value representing the new limit.
fmt -w [n] [file-name]
Here’s an example where width was reduced to 20:
Q3. How to make fmt highlight the first line?
This can be done by making the indentation of the first line different from the rest, which you can do by using the -t command line option.
fmt -t [file-name]
Q4. How to make fmt split long lines?
The fmt command can also split long lines, a feature that you can access using the -s command line option.
fmt -s [file-name]
Here’s an example of this option:
Q5. How to have separate spacing for words and lines?
The fmt command offers a -u option, which ensures one space between words and two between sentences. Here’s how you can use it:
fmt -u [file-name]
Note that this feature was enabled by default in our case.
Conclusion
Agreed, fmt offers limited features, but you can’t say it has a limited audience. You never know when you may need it. In this tutorial, we’ve covered the majority of the command line options that fmt offers. For more details, head to the tool’s man page.