Awk with passed parameters

William R. Pringle wrp at PRC.Unisys.COM
Mon Mar 11 14:06:56 AEST 1991


In article <3022 at dsacg3.dsac.dla.mil> nfs1675 at dsacg3.dsac.dla.mil ( Michael S Figg) writes:
>
>
>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 familar with awk.
>
The following script worked for  me on a BSD machine using Bourne shell:

#!/bin/sh

ls -l | awk '
NR == 1 { nf=split(date,Date," ") } $5 == Date[2] && $6 == Date[3] ' \
	date="`date`" -

I am using the original (old) version of awk here, which is why the
NR == 1 construct.  In this version, arguments passed from the command
line do not become available to the program until after the BEGIN segment
is complete.  This allowed us to set up defaults in the BEGIN segment
and override them from the command line.

Newer versions (nawk, gawk, etc.) make the command line arguments available
immediately.  If you are using one of those, then you could use BEGIN
instead of NR==1.  The above script should work for all flavors of awk.

Incidentally, notice the dash used for file name.  This is usually
optional, and many people omit it, but it is required if you are
passing command line arguments to awk.

Bill Pringle
wrp at prc.unisys.com



More information about the Comp.unix.shell mailing list