Find the answer to your Linux question:
Results 1 to 7 of 7
What i want to do: list all users that have UID > 2000. I know i can find information regarding the user in /etc/passwd and i know how to select ...
  1. #1
    Just Joined!
    Join Date
    Feb 2008
    Posts
    2

    Conditional statements

    What i want to do: list all users that have UID > 2000.
    I know i can find information regarding the user in /etc/passwd and i know how to select only the fields i'm interested in from that file using (cut -f1,3 -d . But what composed command will solve my problem? How to i check if the 3'rd field returned by cat is greater that 2000 ?

  2. #2
    Linux Guru
    Join Date
    Nov 2007
    Location
    Córdoba (Spain)
    Posts
    1,513
    You can use awk for the whole task:

    awk '{FS=":"; if ($3 > 2000) print $1":"$3}' /etc/passwd

  3. #3
    Just Joined!
    Join Date
    Feb 2008
    Posts
    2
    Thanks, that worked! I'm curious though: are there any approaches that don't use awk?

  4. #4
    Linux Guru
    Join Date
    Nov 2007
    Location
    Córdoba (Spain)
    Posts
    1,513
    Quote Originally Posted by Adrian Manolache View Post
    Thanks, that worked! I'm curious though: are there any approaches that don't use awk?

    Sure, this is a bashish approach:

    #!/bin/bash

    cat /etc/passwd | while read line
    do
    a=${line%%:*}
    b=${line%:*:*:*:*}
    b=${b#*:*:}

    if [ "$b" -gt "2000" ]
    then
    echo $a:$b
    fi
    done

  5. #5
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    I prefer to use cut:
    Code:
    #!/bin/bash
    
    exec 3< /etc/passwd
    
    while read line <&3; do
        name=$(echo "$line" | cut -f1 -d:)
        id=$(echo "$line" | cut -f3 -d:)
    
        if [ "$id" -gt 2000 ]; then
            echo "$name"
        fi
    done
    awk is incredibly powerful (and may well be better suited to this problem), but cut is a less powerful alternative in many cases.
    DISTRO=Arch
    Registered Linux User #388732

  6. #6
    Linux User
    Join Date
    Aug 2006
    Posts
    458
    Quote Originally Posted by i92guboj View Post
    awk '{FS=":"; if ($3 > 2000) print $1":"$3}' /etc/passwd
    it is advisable to put FS declaration in the BEGIN block or using -F option
    Code:
    awk 'BEGIN{FS=":"} $3 > 2000 {print ...}' /etc/passwd

  7. #7
    Linux User
    Join Date
    Aug 2006
    Posts
    458
    Quote Originally Posted by Adrian Manolache View Post
    Thanks, that worked! I'm curious though: are there any approaches that don't use awk?
    bash, no cat
    Code:
    while IFS=":" read -r -a line
    do
     if [ ${line[2]} -gt 2000 ];then
       echo ${line[0]} ${line[2]}
     fi
    done < /etc/passwd

Posting Permissions

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