Results 1 to 4 of 4

Thread: More Newbness

  1. #1
    Join Date
    Feb 2004
    Posts
    5

    Unanswered: More Newbness

    I want to take a shell variable and use it in an awk command

    Example:

    >var="Hello People"
    >awk -F":" '$2 == var {print $0}' filename

    Jean thanks in advance, ha, or thanks to who ever else answers these forums.

  2. #2
    Join Date
    Jan 2004
    Location
    Bordeaux, France
    Posts
    320
    Two solutions :

    Play with shell quotes :
    Code:
    var="Hello People"
    awk -F":" '$2 == "'"$var"'" {print $0}' filename
    Executes : awk -F":" '$2 == "Hello People" {print $0}' filename

    The other solution (my prefered) is to use awk variables :
    Code:
    var="Hello People"
    awk -F":" -v awkvar="$var" '$2 == awkvar {print $0}' filename
    Jean-Pierre.

  3. #3
    Join Date
    Jun 2002
    Location
    UK
    Posts
    525
    Hi Micster,

    Just so you don't think JP is out on a limb here, I'll chip in my 2 cents...

    There are 2 ways to pass a variable to awk using awk syntax (there are many others using the shell but we'll ignore that).

    The original method implemented in awk was to declare a variable after the awk command.

    e.g. awk '{print var}' var="hello world"

    The second method was introduced a little later in the life of awk and was implemented in order that a passed variable could be used in a BEGIN block. This uses the -v flag as illustrated by JP.

    Compare the following 2 examples:

    awk -v var="hello world" 'BEGIN {print var}'

    awk 'BEGIN {print var}' var="hello world"

    The second example will not output anything because the variable would only be available in the main body (and the END block).

    I guess this is why the -v method is preferred by most (including myself).

    HTH

  4. #4
    Join Date
    Feb 2004
    Posts
    5
    Man you guys are great! It might seem like small stuff to you guys but I beat my head on this for 6 hours lastnight the whole time cursing mentally at my instructor.

    As always thanks so much!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •