Xref: utzoo comp.unix.questions:29277 comp.unix.shell:1634 Path: utzoo!news-server.csri.toronto.edu!cs.utexas.edu!uunet!convex!news From: tchrist@convex.COM (Tom Christiansen) Newsgroups: comp.unix.questions,comp.unix.shell Subject: Re: Awk with passed parameters Keywords: awk bsd shell Message-ID: <1991Mar08.141340.26881@convex.com> Date: 8 Mar 91 14:13:40 GMT References: <3022@dsacg3.dsac.dla.mil> Sender: news@convex.com (news access account) Reply-To: tchrist@convex.COM (Tom Christiansen) Organization: CONVEX Software Development, Richardson, TX Lines: 51 Nntp-Posting-Host: pixel.convex.com From the keyboard of nfs1675@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