Find the answer to your Linux question:
Results 1 to 2 of 2
I have two files (passwd.txt, group.txt) that I would like to take information out of and put into a new file. I would like to list all the users having ...
  1. #1
    Just Joined!
    Join Date
    Mar 2011
    Posts
    1

    Trying to Sort Two Files

    I have two files (passwd.txt, group.txt) that I would like to take information out of and put into a new file. I would like to list all the users having a shell “/bin/bash” followed by a space separated list of all the groups each user belongs to. I'm brand new to Linux and just trying to organize some things and learn along the way. I would also like to have the new file in alphabetical order, if that is possible.

    I don't think this is that complicated of a task, but since I'm a newb I could use the help. Thanks in advance!

  2. #2
    Linux Newbie Nagarjuna's Avatar
    Join Date
    Feb 2011
    Posts
    122
    Hey, rjdelight. Welcome to Linux-Forums.

    I love questions like these.. They give me a great reason to exercise command-line text manipulation!

    Try the following little script:
    Code:
    #!/bin/bash
    
    users=( $(cat passwd.txt | grep /bin/bash | cut -d: -f1 | sort) )
    
    for i in ${users[@]}; do
    	groups=( $(cat group.txt | grep $i | cut -d: -f1 | sort) )
    	echo $i ':' ${groups[@]} >> users.txt # Add to new file 'users.txt'
    done
    Paste the above into a text file and give it execute permissions:

    Code:
    chmod +x script-name.sh
    Of course the script will need to be in the same working directory of the files to be manipulated. If not, simply edit the paths in the script to match the files location. Now, this will only really work if your .txt files are formatted like the /etc/passwd and /etc/group files are.

    The script creates a BASH array of your users by slicing out the names from the passwd.txt file and sorting them alphabetically. It then goes through each user in the array, cuts out the respected user's groups from the group.txt file and spits them into a file called 'users.txt'.

    I hope this achieves what your looking for. If not, I'll try again!
    Last edited by Nagarjuna; 03-28-2011 at 12:47 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...