LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   awk: /matching/ variables passed with -v (https://www.linuxquestions.org/questions/linux-general-1/awk-matching-variables-passed-with-v-291578/)

aunquarra 02-17-2005 06:26 PM

awk: /matching/ variables passed with -v
 
I was introduced to awk today. Yay for me. I'm actually quite enjoying its flexibility, and I think I may very well have found my new best friend.

That is, if we can learn to get along...

I'm trying to use awk to run through logs looking for an IP address, and counting the times its listed, noting the first and last date, and so forth.

I'm passing a variable with -v (the ip address) so that I can awk for it...

The problem is, it matches it verbatim, rather than as a variable...

In other words, if I do:
awk -v ip='192.168.1.101' -f count.awk /var/log/maillog

and it matches based on /ip/, it's matching "ip", not "192.168.1.101".

I'm sure this is ubersimple, but I've only been working with awk for a couple hours now, and this is my first attempt at a non-hello-world-ish application with it.

frob23 02-17-2005 06:31 PM

This is from a program I wrote a while ago for someone.

Code:

# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# <frob23@yahoo.com> wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return. Eric F.
# ----------------------------------------------------------------------------
BEGIN {
  FS="|";
  notfound=1
        }
{if ($3 == id)
  { print newline; notfound=0}
 else {print $0}
}
END {if (notfound==1)
  print newline
}

Here is the snippet that calls it.

gawk -v id="$ID" -v newline="$LINE" -f updatedata.awk tmpfile >tmp

I hope that helps a little.

Edit: Pay special attention to the bold segments as they should give you an ample hint as to how to do this.

aunquarra 02-17-2005 06:47 PM

Ahh.... Thanks! I didn't think to check that way...

*runs off to invoke the power of awk*


All times are GMT -5. The time now is 08:01 AM.