Wednesday, June 27, 2012
2:41 PM

Formatting text files using fmt

The command fmt allows us to format text file easily.
We saw how to wrap text using the command fold, in the post "Wrapping lines in a text file to specific width"
The command fmt gives more feature than fold gives.
For example let us say we have a file with the following contents
data:



By default fmt wraps text at 75 columns .



The number of columns to be wrapped at can be changed by the option -w



In the above command we have asked fmt to wrap text at 90 columns. If any line does not have requested number of columns fmt by default moves text line to the current line. Thus we seen in the above output that the text "fmt allows" has been moved up to line 1.
But unlike fold, fmt does not split words in between and if the word is exceeding the requested number of columns the whole words is moved to next line.
We can prevent fmt from moving text from the next line if the current line does not have the requested number of columns by using the option "-s"



Thus we can see that only if lines exceed 90 columns it will be wrapped else no new text is added to shorter lines.
Another useful feature of fmt is it can format the spacing between words and lines to be same across the whole file. If we add the "-u" option with the command then every word is separated by one space and every line by two spaces.



We can see in the output that the extra spaces after the words "the" and "allows" has been removed and made into a single space.
The lines that need to be formatted can be restricted by using the option -p



We can see that the line that starts with the string "This" is only formatted and the next line is not formatted.
Thus the basic formatting of text files is pretty easy using fmt.

0 comments:

Post a Comment