Awk with passed parameters

Tom Christiansen tchrist at convex.COM
Sat Mar 9 00:13:40 AEST 1991


>From the keyboard of nfs1675 at dsacg3.dsac.dla.mil ( Michael S Figg):
:I'm trying to write a short shell script using awk to list files in the
:current directory that have todays' date on them. It seems like something
:like this should work, but I haven't had any luck:
:
:set d = `date`
:ls -l | awk '$5 == x && $6 == y  {print}' x=$d[2] y=$d[3]
:
:This in a C shell on a BSD machine where $5 is the month and $6 is the day.
:I've also tried this on a SVR3.2 machine with a Bourne shell and get similar
:results, usually that it can't open "Mar", which I'm assuming is coming from
:the 'x=$d[2]'. Any clues on what I'm doing wrong?  I'm sure there are other
:ways to do this, but I'd like to get more familiar with awk.

The first thing is that you need to put your variable assignments
in front of your program.  You probably should protect your string
literals with double quotes so it doesn't think they are variables.

#!/bin/csh -f
set d = `date`
ls -l | awk x='"'$d[2]'"' y='"'$d[3]'"' '$5 == x && $6 == y  {print}' 

(Isn't quoting *fun* in the csh?)

However, to my dismay I found that this is entirely rejected by
the standard awk distributed with most systems.  Nawk was able
to handle the first assignment, but got all confused by the time
we hit the second one.  Only gawk did the right thing with this code.

What you could do then is just embed the assignments in a BEGIN block:

#!/bin/csh -f
set d = `date`
ls -l | awk 'BEGIN { x = "'"$d[2]"'"; y = "'"$d[3]"'"} $5 == x && $6 == y  {print}' 

This will work on all three versions of awk.

You might consider using the real shell for your scripts.  It will pay
off again and again.

#!/bin/sh
set `date`
ls -l | awk "BEGIN { x = \"$2\"; y = \"$3\"} \$5 == x && \$6 == y  {print}"

quoting is certainly easier, and there are other very good reasons as well.

On the other hand, after seeing what a pain this is, you might begin
to understand why I so often just throw out the whole shebang and
write it in perl instead.

--tom



More information about the Comp.unix.shell mailing list