Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am looking to find a way to script a cleaning operation on the /etc/group file on a large number of servers. Looking for users in a particular group more than once.

i.e. somegroup::100000:userA, userB, userC, foo, bar, snafu, userB, userB

Obviously for a small group this is easy and can be done manually, but I have some group files with large numbers of groups and entries.

I thought about writing it up in java since it should be pretty easy, but I would prefer finding something in perl or shell.



share|improve this question

Here's a Perl script to do it.

while (<>) {
    my ($name, $pass, $gid, $users) = split ':';
    my %userset;
    my @users = split ',', $users;
    # create a set (a hash with undef keys) by assigning to hash slice
    @userset{@users} = ();
    $users = join ',', sort(keys(%userset));
    print join(':', $name, $pass, $gid, $users). "\n";

Use it like this:

$ ./fixgroups <group >group.tmp
$ diff -u group group.tmp
$ mv group.tmp group
share|improve this answer
You might want to keep the old group file as a back-out point just in case. Also before copying the new group file use the command 'grpck' to check if the new group file is actually valid. – DarkHeart May 6 '12 at 7:48
Gents/Ladies -- thanks so much! – ssbob May 6 '12 at 20:28
You're welcome. If it helped, please accept the answer. – Mikel May 6 '12 at 21:26

Your Answer


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

Not the answer you're looking for? Browse other questions tagged or ask your own question.