Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!snorkelwacker.mit.edu!bloom-picayune.mit.edu!athena.mit.edu!jik From: jik@athena.mit.edu (Jonathan I. Kamens) Newsgroups: comp.unix.shell Subject: Re: awk question Message-ID: <1991Feb28.045112.23709@athena.mit.edu> Date: 28 Feb 91 04:51:12 GMT References: <62322@eerie.acsu.Buffalo.EDU> Sender: news@athena.mit.edu (News system) Organization: Massachusetts Institute of Technology Lines: 37 In article <62322@eerie.acsu.Buffalo.EDU>, haozhou@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@Athena.MIT.EDU Allston, MA 02134 Office: 617-253-8085 Home: 617-782-0710