0

How can I list all users with their username and group-name in UNIX systems?

I want to take report form /etc/passwd file and /etc/group file

In passwd file, I'll get only GIDS but I also want to get group-name from /etc/group, and it should come in one report like I want below mention Fotomat

User neme ( user ID) , Group name ,

2
  • 3
    Accounts may exist outside of /etc/passwd...
    – Jeff Schaller
    Commented Feb 23, 2018 at 12:03
  • I echo what Jeff is saying. Accounts may exist out of /etc/passwd... Commented Feb 23, 2018 at 20:32

2 Answers 2

3

With single awk command:

awk -F':' 'NR==FNR{ a[$3]=$1; next }{ print $1", "a[$4] }' /etc/group /etc/passwd
  • -F':' - field separator
  • NR==FNR{ a[$3]=$1; next } - processing the 1st input file (i.e. /etc/group):
    • a[$3]=$1 - capture group name $1 using group identifier $3 as array a key
    • next - jump to next record
  • { print $1", "a[$4] } - action for the 2nd input file (i.e. /etc/passwd):
    • $1 - the 1st field; indicating user name
    • a[$4] - get group name by group id (presented by field $4)
3
  • very good, thanks for explaining this +1
    – alpha
    Commented Feb 23, 2018 at 11:21
  • @DeclanGallagher, you're welcome Commented Feb 23, 2018 at 11:22
  • its working fine with Red hat and AIX fine , but i am trying to do same in the SUNOS i am getting some different format its giving line by line , report i want to get like first Group , name but in sunos its giving one by one @RomanPerekhrest
    – user266746
    Commented Mar 5, 2018 at 5:08
0

The following does a relational JOIN on the two files on the GID and outputs the username and group name with a : in-between:

join -t : -1 4 -2 3 -o 1.1,2.1 \
    <( sort -t : -k4,4 /etc/passwd ) \
    <( sort -t : -k3,3 /etc/group )

The GID is in column 4 in the passwd file and in column 3 in the group file.

With -1 and -2 we specify what the join field is in the two input files and with -o we specify what fields we want to output from each file (the first field of each file).

The sorting of each file on the join field in necessary for join to work.

To get this in the exact format requested, just pipe it though sed 's/:/, /' which replaces the colons with comma and space.

You must log in to answer this question.