#! /bin/sh # Test: # ./fmtAwk.sh file.txt 30 | gawk '{print length($0)}' | sort -g # fmtAwk: Format text into 80-char lines (80 is default, add 2nd arg to change). # Add 3rd arg to use DOS output format instead of Unix output format. if test $# = 0 then >&2 printf '%s\n' '1st arg: file, 2nd arg: string length, 3rd arg: DOS format' exit 1 fi gawk ' {sub(/\r$/, "")} /[^[:cntrl:][:space:]]/ {for (i = 1; i <= NF; i++) addword($i)} /^[[:cntrl:][:space:]]*$/ {printline(); print "'${3:+\\r}'"} END {printline()} function addword(w) { if (length(line) + length(w) + 1 > '${2:-80}') printline() line = line space w space = " " } function printline() { if (length(line) > 0) print line "'${3:+\\r}'" line = space = "" # reset for next line } ' "$1"