5

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?

6
  • Once we get a better idea of what's going on, please edit the title to make it more useful for future use.
    – phk
    Dec 17, 2017 at 11:16
  • 2
    I can answer only the second part. fmt tries to avoid line breaks before the last word of a sentence (as per info fmt). So it tries to avoid e alone on the last line.
    – janos
    Dec 17, 2017 at 11:45
  • 1
    If fmt is meant for re-flowing plain text, single-character words and such a low number of columns probably aren't something it's really meant for... If that's what you actually want to work with, there might be better tools
    – ilkkachu
    Dec 17, 2017 at 12:36
  • @janos, but that sounds like an answer to the question as stated...
    – ilkkachu
    Dec 17, 2017 at 12:37
  • I want to clarify: In some text, that I generated with fmt, I had a strange looking output and thought that maybe I misunderstood how to use fmt. So I played around with the parameters and ended up with the above "minimal examples". I think my intuition that "narrowing down the maneuvering space" for fmt will produce a "less heuristic" result lead to a question that maybe has no useful answer.(1/2)
    – Thomas
    Dec 18, 2017 at 7:12

2 Answers 2

0

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.

0

The intended result can be obtained also with xargs, as in:

printf "a b c d e\n" | xargs -n2 -d" "

producing

a b
c d
e

And not just for single characters:

printf "one two three four five\n" | xargs -n2 -d" "

producing:

one two
three four
five

Best wishes ... cheers, drl

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .