Awk question

Kris Stephens [Hail Eris!] krs at uts.amdahl.com
Tue Jan 22 04:04:16 AEST 1991


In article <681 at silence.princeton.nj.us> jay at silence.princeton.nj.us (Jay Plett) writes:
>In article <1991Jan20.062150.24582 at convex.com>, tchrist at convex.COM (Tom Christiansen) writes:
>- From the keyboard of bob at wyse.UUCP (Bob McGowen x4312 dept208):
>- :In article <1991Jan18.164243.11804 at cbnewsh.att.com> me at cbnewsh.att.com (william.j.bruncati) writes:
>- :>This doesn't work. It won't give me a match although there is one.
>- :>		if (myarray[i] ~ /$1/ )
>- :>			print $0
>- :
>- :  I believe this is because you are using "old" awk, which did not
>- :  allow substitution into patterns, as with your "/$1/".
>- 
>- And if like so many all you have is the old awk, get gawk, which is free.
>
>Either nawk or gawk are worth having.  But I don't believe that either
>of them will solve the stated problem.
>
>I've never been able to find a way to use a variable on the right-hand
>side of a ~ expression with any of the incarnations of awk.  Have I
>missed something?

Well, in nawk, this works...

	if ( match(myarray[i], $1) > 0 ) {
		print "record", NR, "matched somewhere on entry", i
		print $0
		}
	if ( match(myarray[i], $1) == 1 ) {
		print "record", NR, "matched start of array item", i
		print $0
		}

In a related vein, I often do something like this...

	BEGIN {
		keywords = " first second third "
		ebadkey = "invalid keyword '%s' on record %d\n"
		}

	#
	# Handle a valid keyword
	#
	$1 == "key" && match(keywords, " " $2 " " {
		print "I'd do something with the key, " $2 ", here."
		next
		}

	#
	# Bad keyword record!
	#
	$1 == "key" {
		printf(ebadkey, $2, NR) | "/bin/cat 1>&2"
		errorcount++
		next
		}

	#
	# Report error count
	#
	END {
		if ( errorcount > 0 )
			print errorcount, "errors found" | "/bin/cat 1>&2"
		}

...Kris
-- 
Kristopher Stephens, | (408-746-6047) | krs at uts.amdahl.com | KC6DFS
Amdahl Corporation   |                |                    |
     [The opinions expressed above are mine, solely, and do not    ]
     [necessarily reflect the opinions or policies of Amdahl Corp. ]



More information about the Comp.unix.shell mailing list