0

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.

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

4 Answers 4

2
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.

0

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

Using awk seems to be the better choice.

0

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
0

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.

You must log in to answer this question.