List users in Linux

Viewed 154

How can I list in alphabetical order all users and also for the first 10 users to see user ID info (column 5). I know for the first part of the question that I can use like cat /etc/passwd | cut -d ':' -f1, but how about the second part? should i use "for" or "if" or something like this?

2 Answers

Remove the header with grep and use cut:

cat /etc/passwd | grep -v '^#' | cut -d: -f1,5

Using GNU awk:

  awk -F: '{ 
              users[cnt++]=$1 # Set up an array with the users (first : separated field) as the value 
           } 
       END { 
              PROCINFO["sorted_in"]="@val_str_asc"; Set the array sort order to value ascending
              for ( i in users ) { # Loop through each entry in the array
                                   if ( cnt1 <= 4) { # Only print the first 5
                                                      print users[i];
                                                      cnt1++ # Use to track number of prints
                                   } 
              } 
            }' /etc/passwd

One liner

 awk -F: '{ users[cnt++]=$1 } END { PROCINFO["sorted_in"]="@val_str_asc";for ( i in users ) { if ( cnt1 <= 4) { print users[i];cnt1++ } } }' /etc/passwd
Related