awk

This is a discussion on awk within the Linux Programming forums, part of the Platform Specific Boards category; hello i'm writing a bash script and i want to use a command and filter it with awk,I do the ...

  1. #1
    quo
    quo is offline
    Registered User
    Join Date
    May 2011
    Posts
    116

    awk

    hello

    i'm writing a bash script and i want to use a command and filter it with awk,I do the following:

    Code:
    last | grep -v "wtmp" | awk '{print $3}'
    but i want awk to print column 3 only if column 1 (which is the username) matches the variable $usr
    Is there a way to do this comparison in awk?

    thanks

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,418
    A couple of ways...
    Code:
    $ last | grep -v "wtmp" | awk -v u=$USER '$1==u {print $3}'
    $ last | grep -v "wtmp" | awk  '$1==ENVIRON["USER"] {print $3}'
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    quo
    quo is offline
    Registered User
    Join Date
    May 2011
    Posts
    116
    Quote Originally Posted by Salem View Post
    A couple of ways...
    Code:
    $ last | grep -v "wtmp" | awk -v u=$USER '$1==u {print $3}'
    $ last | grep -v "wtmp" | awk  '$1==ENVIRON["USER"] {print $3}'
    thanks a lot!

  4. #4
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    You should be able to get rid of the grep invocation something like this
    Code:
    $ last | awk -v u=$usr '!/wtmp/ && $1==u {print $3}'
    I don't know what column "wtmp" occurs in, but if it's in the user name column and $usr is not "wtmp", then just
    Code:
    $ last | awk -v u=$usr '$1==u {print $3}'
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21