Skip to main content

Hard wrap hard refill [Resolved]

Given this file:

$ cat file
alfa bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike
november oscar papa quebec romeo sierra tango
uniform_victor_whiskey_xray yankee zulu

I would like to hard break at 70, but I would also like to hard refill. I tried "fold", but it did not refill:

$ fold -w 70 file
alfa bravo charlie delta echo foxtrot golf hotel india juliet kilo lim
a mike
november oscar papa quebec romeo sierra tango
uniform_victor_whiskey_xray yankee zulu

"fmt" will refill, but I could only get it to break on spaces so no guarantee to wrap on exactly 70:

$ fmt file
alfa bravo charlie delta echo foxtrot golf hotel india juliet
kilo lima mike november oscar papa quebec romeo sierra tango
uniform_victor_whiskey_xray yankee zulu

I tried "pr" but it seems to just truncate the line without wrapping:

$ pr -t -W 70 file
alfa bravo charlie delta echo foxtrot golf hotel india juliet kilo lim
november oscar papa quebec romeo sierra tango
uniform_victor_whiskey_xray yankee zulu

Maybe these commands have some option I am missing, or maybe Awk or Sed solution. I would prefer to avoid heavier solutions (Perl PHP Ruby).


Question Credit: Steven Penny
Question Reference
Asked October 10, 2018
Tags: shell, wrap
Posted Under: Unix Linux
15 views
2 Answers

Using sed

With GNU sed:

$ sed -zE 's/\n/ /g; s/.{70}/&\n/g; s/$/\n/' file
alfa bravo charlie delta echo foxtrot golf hotel india juliet kilo lim
a mike november oscar papa quebec romeo sierra tango uniform_victor_wh
iskey_xray yankee zulu 

With any POSIX sed:

sed -zE 'H;1h;$!d;x; s/\n/ /g; s/.{70}/&\n/g; s/$/\n/' file

Using awk

$ awk  '{r=(length(r)?r" "$0:$0); while(length(r)>70){print substr(r,1,70); r=substr(r,71)}} END{print r}' file
alfa bravo charlie delta echo foxtrot golf hotel india juliet kilo lim
a mike november oscar papa quebec romeo sierra tango uniform_victor_wh
iskey_xray yankee zulu

With tr and fold

$ tr '\n' ' ' <file | fold -w 70
alfa bravo charlie delta echo foxtrot golf hotel india juliet kilo lim
a mike november oscar papa quebec romeo sierra tango uniform_victor_wh
iskey_xray yankee zulu

The above does not produce a trailing newline but we can add one if needed with echo "":

tr '\n' ' ' <file | fold -w 70; echo

credit: Steven Penny
Answered October 10, 2018

This wont work in all cases, but it should cover most use cases:

$ fmt -w 2500 file | fold -w 70
alfa bravo charlie delta echo foxtrot golf hotel india juliet kilo lim
a mike november oscar papa quebec romeo sierra tango uniform_victor_wh
iskey_xray yankee zulu

credit: Steven Penny
Answered October 10, 2018
Your Answer
D:\Adnan\Candoerz\CandoProject\vQA