Thread: awk

  1. #1
    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 int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    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.

  3. #3
    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