Textwrapping with FOLD and FMT

If you are on a Unix based system, such as a Mac or Ubuntu, then you already have two tools built-in to help with wrapping text: fold & fmt. I’ll be explaining how these two tools both do text-wrapping but in slightly different ways.

Setup

For our example we’ll be using a text.txt file as the input with the data:

Garrus Vakarian is a super-badass.

To see the difference in whitespace changes, I will be using the • character in the outputs below.

FOLD

The basic format for the fold command is:

fold -w <num> <file>

The -w option for width in columns (e.g. characters) where the text wrapping will start. The file is the target of the text wrapping we want to apply this to.

fold -w 10 text.txt will output:

Garrus•Vak

arian•is•a

•super-bad

ass.

Adding the -s option will define wrapping to start only after a space character when possible.

fold -s -w 10 text.txt will output:

Garrus•

Vakarian•

is•a•

super-bada

ss.

As seen in the above example, fold will force a fold in the middle of a word that is longer than our argument (in our example 10).

FMT

The basic format for the fmt command is:

fmt -w <num> <file>

The -w option for width in columns (e.g. characters) where the text wrapping will start. The file is the target of the text wrapping we want to apply this to.

fmt -w 10 text.txt

Garrus

Vakarian

is•a

super-badass.

The fmt command breaks the lines at their whitespace, while also removing the whitespace at the text-wrap point. Also, words that are longer than the defined width will not be broken.

Leave a Reply

Your email address will not be published. Required fields are marked *