I have a task to write to file the list of login names, full names and home directories of all users whose first character of their full name (not login name) is "A" or "Z"(process the file /etc/passwd).
I tried with
> cat /etc/passwd | grep -i '^A\|^Z' > ex.list
But it also outputs users who have first name starting with other letter than A or Z. How to change it ?
CodePudding user response:
- Use
getentto obtain thepasswdentries regardless if it is a local/etc/passwdfile or a Networked Information Service. - Use
awkto filter the desired user entries, then prints their real name and home directory properties.
getent passwd | awk -F: '$5 ~ /^[AZ]/{printf("%s\t%s\n", $5, $6)}'
awk -F:: invokeawkwith:as field delimiter.
The awk program itself
# Filter field 5 containing Real Name
# and regex match it starts with upper-case A or Z
$5 ~ /^[AZ]/{
# For each selected entry
# Print a tab formatted list with fields 5 and 6
# witch contains the Real-Name and Home Directory
printf("%s\t%s\n", $5, $6)
}
