How To: find usernames of at least four characters
I’ve recently been asked a few questions about identifying users on your Unix system using various criteria, so today I’ll answer one of such questions.
Find usernames of a certain length
The original question was to find a list of users with usernames longer than 4 characters. The task of answering this question is split into three steps:
- Getting the list of users or user accounts information
- Extracting usernames from the input data
- Filtering the usernames list using our criteria
The reason I have these two steps separated is because depending on your need, you may have to look at currently logged in users, or users which were logged into your system in the past, or even all the users known to your system (/etc/passwd ones or even users with account information held in LDAP or NIS).
Once you get the list though, the second step of filtering through such a list can always remain the same. This will allow for the same code to be reused.
Getting the list of currently logged in users
The list of users currently working on your system is generated by the who command:
bash-2.03$ who gr pts/0 Apr 8 09:17 (myserver1) gr pts/4 Apr 8 09:18 (myserver1) greys pts/8 Dec 10 14:21 (myserver2) gleb pts/17 Mar 27 12:26 (myserver3) To get a list of users who were logged into your system in the past, use the last command: $ last If you're trying to sort through all the users known to your system, you may have to consult the /etc/passwd file: cat /etc/passwd If your system is part of a network, there's a good chance it uses centralized mechanism for managing user accounts, something like NIS or LDAP. To make sure you contact them for the full list of users, use the getent command: bash$ getent Filtering text with awk awk is a very useful string processor, and we're going to use it for filtering through our lists. You can either pipe the output of a command to it, or specify a name of the file to be processed. Just so that we can test awk to be working, here's a simple example which doesn't do anything with your text, just prints it out: who | awk '{print}' Now that we confirmed this to be working, let's start processing the data. First, let's use the power of awk to split input lines into fields, and to only output the usernames: who | awk '{print $1}' In this example, $1 stands for the first field in a space-delimitered string - the usernames in the output of who command. Since we're only interested in the usernames longer than 4 characters, we're going to use one of the built-in functions of the awk scripting language, which deals with length of any given parameter: bash-2.03$ awk -F: '{if (length($1)>4) print $1 }' /etc/passwd daemon nuucp listen nobody noaccess nobody4 bbuser iscan