Search code examples
linuxsortinggrepetcpasswd

Linux usernames /etc/passwd listing


I want to print the longest and shortest username found in /etc/passwd. If I run the code below it works fine for the shortest (head -1), but doesn't run for (sort -n |tail -1 | awk '{print $2}). Can anyone help me figure out what's wrong?

#!/bin/bash

grep -Eo '^([^:]+)' /etc/passwd | 
while read NAME
do
  echo ${#NAME} ${NAME}
done |
sort -n |head -1 | awk '{print $2}' 
sort -n |tail -1 | awk '{print $2}'

Solution

  • If you want both the head and the tail from the same input, you may want something like sed -e 1b -e '$!d' after you sort the data to get the top and bottom lines using sed.

    So your script would be:

    #!/bin/bash
    grep -Eo '^([^:]+)' /etc/passwd | 
    while read NAME
    do
      echo ${#NAME} ${NAME}
    done |
    sort -n |  sed -e 1b -e '$!d'
    

    Alternatively, a shorter way:

    cut -d":" -f1 /etc/passwd | awk '{ print length, $0 }' | sort -n | cut -d" " -f2- | sed -e 1b -e '$!d'