Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I am trying to use a single command to scan /etc/passwd for the gecos field in the format "User (userid) is (Real name)" so output would be "User brian is Brian". I have been trying for a good hour and cannot come up with a good solution. I'm sure i need to use grep but cannot figure out a good way to do it.

share|improve this question

migrated from stackoverflow.com Sep 24 '12 at 17:25

This question came from our site for professional and enthusiast programmers.

2  
Is that not a job for awk (or Perl, Python, ...)? –  Pascal Cuoq Dec 1 '10 at 5:42
    
Yeah that could be. –  brian Dec 1 '10 at 5:46
add comment

4 Answers

awk -F: '$1=="brian" {print "User", $1, "is", $8}' /etc/passwd

Leave out the $1=="brian" if you want to print every line in the file.

share|improve this answer
add comment

awk -F \: '{print "User ", $1, "is ", $5;}' /etc/passwd

Using awk seems to be the better choice.

share|improve this answer
add comment

Per Pascal's comment you'll need to use a utility like awk (or Perl, Python, Ruby, etc). This awk command will work for passwd files with comma-separated GECOS fields with the user's real name first:

awk -F: '{split($5,a,","); print "User "$1" is "a[1]}' /etc/passwd
share|improve this answer
add comment

Your question is a bit vague, but all the answers thus far solve the problem of parsing the passwd line into your format. However, your suggestion for using grep makes me think you are interested in also picking a specific entry rather than printing out a line for every user on the system.

grep is certainly one possibility for this, but I find the getent command to be a cleaner way to get entries from the passwd file.

Since there are so many awk based solutions, I have attempted to do the parsing with sed in stead. This is merely to have a more colourful set of answers, I would not consider it better or simpler for the task.

#!/bin/bash
if [[ $# != 1 ]]; then
    echo "$0: wrong number of arguments"
    echo -n "Usage: "
    echo "$0 {username | UID}"
fi

getent passwd "$1" \
    | sed 's/\(.*\):.*:.*:.*:\(.*\):.*:.*$/User \1 is \2/'

Extending the script to take an arbitrary number of arguments is left an exercise for the reader.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.