Shell – Understanding fmt (gnu coreutils)

coreutilsshell

I'm using fmt (GNU coreutils) 8.25 and I fail to understand how to use it.
In particular, I don't understand the following results.

  1. $ echo -n "a b c d e" | fmt -w3 -g3

    I expected to obtain

    a b
    c d
    e
    

    but I get

    a 
    b
    c 
    d
    e
    

    So I thought maybe fmt counts the linebreak it inserts and tried

  2. $ echo -n "a b c d e" | fmt -w4 -g4

    But then, I get:

    a
    b c
    d e
    

    Finally, I don't get the following:

  3. $ echo -n "a b c d e" | fmt -w4 -g1
    which I expected to give

    a 
    b
    c 
    d
    e
    

    but instead again results in

    a
    b c
    d e
    

So, obviously I'm failing to understand how the -w and -g options work.
Could someone please explain the output of my three examples?

Best Answer

It won't answer your question about coreutils' fmt, but you can solve your string manipulation cases with sed as well:

printf "a b c d e\n" | sed 's/.\{1\} .\{1\} /&\n/g'

result:

a b 
c d 
e

.\{1\} corresponds to a single character.