From owner-freebsd-questions Fri Oct 5 0:12: 2 2001 Delivered-To: freebsd-questions@freebsd.org Received: from guru.mired.org (okc-65-31-203-60.mmcable.com [65.31.203.60]) by hub.freebsd.org (Postfix) with SMTP id BDB7537B401 for ; Fri, 5 Oct 2001 00:11:56 -0700 (PDT) Received: (qmail 82812 invoked by uid 100); 5 Oct 2001 07:11:56 -0000 From: Mike Meyer MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Message-ID: <15293.23868.39354.690746@guru.mired.org> Date: Fri, 5 Oct 2001 02:11:56 -0500 To: Chris Fedde Cc: questions@freebsd.org, Subject: Re: Real dumb shell script/awk question In-Reply-To: <32463104@toto.iv> X-Mailer: VM 6.90 under 21.1 (patch 14) "Cuyahoga Valley" XEmacs Lucid X-face: "5Mnwy%?j>IIV\)A=):rjWL~NB2aH[}Yq8Z=u~vJ`"(,&SiLvbbz2W`;h9L,Yg`+vb1>RG% *h+%X^n0EZd>TM8_IB;a8F?(Fb"lw'IgCoyM.[Lg#r\ Sender: owner-freebsd-questions@FreeBSD.ORG Precedence: bulk List-ID: List-Archive: (Web Archive) List-Help: (List Instructions) List-Subscribe: List-Unsubscribe: X-Loop: FreeBSD.ORG Chris Fedde types: > On Thu, 4 Oct 2001 17:46:53 -0700 "Kory Hamzeh" wrote: > +------------------ > | > | I need to bang together a simple shell script to parse a flat ascii > | database. The fields are variable width, but each field is separated by the > | "|" character. Basically, all this script needs to do is to read the > | database, one line at a line, and if field X is equal to value Y, then print > | the value of field Z. The user must be able to specify X, Y, and Z on the > | command line. > | > | Now, for the life of me, I can't seem to figure out a simple way of doing > | this with a bourne shell script. I think awk can do it, but the man pages > | didn't help me too much with the language. I know other language, like perl, > | are probably better suited, but I need to customize this script per the > | clients request, and it will only be needed for a couple of weeks and he'll > | never need this again. > | > | Any tips on how to do this? I'm sure there is a simple way and I'm drawing a > | blank. > +------------------ > Awk is your friend But metacharacters are your enemy. > $ cat t > asdf|trew|agfd > asdf|asdf|435 > wer|asgf|bwhw > qwert|qewrt|asdf > > $ awk -F'|' -e '$1 == $2 {print $3}' t > 435 That tests field values, not a user-supplied value, and -e isn't an awk option. bash-2.05$ cat test #!/bin/sh # $1 = X, $2 = Y, $3 = Z awk -F'|' "\$$1 == $2 {print \$$3}" bash-2.05$ cat t asdf|trew|agfd asdf|asdf|435 wer|asgf|bwhw qwert|qewrt|asdf bash-2.05$ sh test 3 435 1 < t asdf bash-2.05$ Adding simple argument checking is probably worthwhile, as otherwise awk complains. http://www.mired.org/home/mwm/ Q: How do you make the gods laugh? A: Tell them your plans. To Unsubscribe: send mail to majordomo@FreeBSD.org with "unsubscribe freebsd-questions" in the body of the message