-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfmt.ksh
executable file
·67 lines (63 loc) · 1.7 KB
/
fmt.ksh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#! /bin/ksh
# Format text from stdin to be lines containing no more than the specified
# number of characters.
# Written in KornShell; no filters required
function printusage {
msg="Usage: $0 [-c columns]"
print "$msg"
status=1
}
PATH=/usr/bin
maxlinelen=72
status=0 # initialize exit status
# process command line options
while getopts ":c:" option
do
case $option in
c) if [[ $OPTARG != +([0-9]) ]] ; then
printusage
else
maxlinelen=$OPTARG
fi
;;
*) printusage
;;
esac
done
shift $(( OPTIND - 1 ))
if [[ $# -ne 0 ]] ; then
printusage
fi
# do the formatting
if [[ $status -eq 0 ]] ; then
linelen=0
while read line ; do
if [[ $line == *([ ]) ]] ; then # blank line, so end this paragraph
print # end current line
print # leave a blank line
linelen=0
else
for word in $line; do
wordlen=${#word}
if [[ $linelen -eq 0 ]] ; then # first word of new paragraph
print -nr -- "$word"
linelen=$wordlen
else
(( newlinelen = linelen + 1 + wordlen ))
if [[ $newlinelen -gt $maxlinelen ]] ; then
print
print -nr -- "$word"
linelen=$wordlen
else
print -nr -- " $word"
linelen=$newlinelen
fi
fi
done
fi
done
if [[ $linelen -gt 0 ]] ; then
print # finish final line
fi
fi
exit $status