[comp.unix.questions] awk format pgm

dbar@ecst.csuchico.edu (David Barrett) (04/13/91)

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 }.

tchrist@convex.COM (Tom Christiansen) (04/13/91)

You have an awk that doesn't understand functions.  Get one that does,
or run it through a2p so you can run perl on it.  Or get the BSD version
written in C off uunet.

--tom

PS: This is the third of these articles I've seen; they seem to have
    been posted three separate times.  Please don't do that. Use the 
    newsgroups line instead to list the various newsgroups; this 
    would safe time and space.

fitz@mml0.meche.rpi.edu (Brian Fitzgerald) (04/13/91)

David Barrett writes:

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.

...
>function addword(w) {
 ^^^^^^^^
...

You need new awk.  A public domain implementation version called "gawk"
(for gnu awk) is available by anonymous ftp from prep.ai.mit.edu in
/pub/gnu.  You may also need bison and gcc to compile gawk, and tex to
print the manual, so it might be simpler just get gawk from your site
gnu guru.

Brian

jim@segue.segue.com (Jim Balter) (04/15/91)

In article <b4gg+q=@rpi.edu> fitz@mml0.meche.rpi.edu (Brian Fitzgerald) writes:
>You need new awk.

He may well have it.  It is available under SysV as /usr/bin/nawk