awk format pgm

David Barrett dbar at ecst.csuchico.edu
Sat Apr 13 09:56:02 AEST 1991


Who is good with awk?  I have taken an awk script from page 120 of The Awk
Programming Language, by Aho, Kernighan and Weinberger, and tried to get
it to work.  No luck.  The program is called 'fmt' and is intended
to even out the ragged right margin of a text file.  (It does not justify
the lines, only adjusts line lengths to length less than 60 characters.)

Here is the script:

/./   { for (i = 1; i <= NF; i++) addword($i) }
/^$/  { printline(); print "" }
END   { printline() }

function addword(w) {
	if (length(line) + length(w) > 60)
		printline()
	line = line " " w
}

function printline() {
	if (length(line) > 0) {
		print substr(line, 2)
		line = ""
	}
}

After storing this script in file "fmt", I give the command 
"awk -f fmt sourcefile", where sourcefile is a text file to be formatted.
I get compiler messages from awk, as follows.

awk: syntax error near line 2
awk: illegal statement near line 2
awk: syntax error near line 3
awk: illegal statement near line 3
awk: bailing out near line 5

If this little script worked (and also were implemented more conveniently
as a shell script called 'fmt') it could be useful as a margin-adjust macro 
that could be invoked from vi command mode.  e.g. to adjust margin of a 
paragraph from which you have just added or deleted words from, press 
CNTL-A, where CNTL-A is defined in .exrc file as as: 

                              map ^A  !}fmt

and ^M is the sequence cntl-V cntl-<CR>

To format whole file, substitute G for }.



More information about the Comp.unix.questions mailing list