Shell – Print man pages with fixed width

command linemanshelltext formattingtext processing

With the example command

man apropos > outputfile

a text file is generated which contains the formatted man page of apropos (with some little differences with respect to man apropos directly printed on screen, such as bold characters).

But I would like to manually set the maximum line width of the generated output file, so that all the paragraphs will be justified to that width.

man pages are created through groff: for example, I tried to put .ll 50 before a paragraph of the original .gz man source text file, but it is trivial if I need to work on several man pages. Moreover not all the characters are recognized:

apropos.1:45: warning: can't find character with input code 195
apropos.1:45: warning: can't find character with input code 168
apropos.1:47: warning: can't find character with input code 178
apropos.1:131: warning: can't find character with input code 169

So, I wonder if a more straightforward method exists. How to modify the maximum line width, during the creation of an outputfile? Is there some specific command?


Edit:

(All the following considerations are about Ubuntu 18.04: I can no more test them in previous versions, included the 14.04 of the above question.)

As regards a one-line temporary solution, if MANWIDTH has not been already exported with a custom value, there is no difference between

$ MANWIDTH=60 man apropos > outputfile

and

$ COLUMNS=60 man apropos > outputfile

The first one, using MANWIDTH, is however better in principle.


Edit 2 (not strictly related to the question):

To make instead a permanent width setting to be applied to any manpage printing, it is necessary to export the desired value of the variable. With:

$ export MANWIDTH=60
# zero or more additional lines
$ man apropos > outputfile

man apropos will be printed with the same width regardless of any terminal window resizing. Instead,

$ export COLUMNS=60
# zero or more additional lines
$ man apropos > outputfile

will provide the same result as before only if the terminal window is not resized between export and man <page> > outputfile.

Best Answer

Use the MANWIDTH environment variable:

MANWIDTH=60 man apropos > apropos.txt

The manpage for man 2.7.4 says:

If $MANWIDTH is set, its value is used as the line length for which manual pages should be formatted. If it is not set, manual pages will be formatted with a line length appropriate to the current terminal (using the value of $COLUMNS, an ioctl(2) if available, or falling back to 80 characters if neither is available).

That is, it overrides both COLUMNS and the ioctl value. I prefer to not rely on modifying COLUMNS (although it does work here) since its value is updated dynamically every time the window size changes.

Using MANWIDTH instead of COLUMNS also allows you to make the change permanent by adding a line such as export MANWIDTH=60 to your shell startup file.

Related Question