awk question

Jonathan I. Kamens jik at athena.mit.edu
Thu Feb 28 15:51:12 AEST 1991


In article <62322 at eerie.acsu.Buffalo.EDU>, haozhou at acsu.buffalo.edu (Hao Zhou) writes:
|> 	prev = 'initialization'
|> 	awk '{{if (condition) \
|> 		printf("%s \n %s \n", $prev, $0)} 
|> 	      {prev=$0}}'
|> 
|> However the variable prev doesn't store the previous line. Instead the
|> printf prints out twice the current line. What am I doing wrong?

  First of all, what is the first line of the script,

    prev = 'initialization'

supposed to be doing?  Since that command appears outside of the awk command,
it sets a shell variable, not an awk variable!

  Second, variables in awk are not referred to using '$' -- only line fields
are.  So the "$prev" in the printf above should just be "prev".  It's likely
that in "$prev", prev is getting interpreted as a number, and since it's a
string awk ends up thinking that it's equal to 0, and therefore uses $0, which
is why the same line prints twice.

  Third, where's the condition?

  It looks to me like you tried to cut down the code you're actually using in
order to post a short example to the net, and you managed to butcher it up
enough in the process that it's not easy for us to help you.  But I'll try:

    awk 'BEGIN { prev = "" }
    { if (condition) prinf("%s\n%s\n", prev, $0) }
    { prev = $0 }'

-- 
Jonathan Kamens			              USnail:
MIT Project Athena				11 Ashford Terrace
jik at Athena.MIT.EDU				Allston, MA  02134
Office: 617-253-8085			      Home: 617-782-0710



More information about the Comp.unix.shell mailing list