LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Extracting all group members (https://www.linuxquestions.org/questions/programming-9/extracting-all-group-members-4175437431/)

a2326 11-16-2012 09:08 AM

Extracting all group members
 
Hello,
I want to extract all members of a group, but I don't get the output that I want:
Code:

GROUP=groupname
cat /etc/group | grep --regex "^"$GROUP":.*" | awk -F:, '{print $4}'

I would like to have an output with one user per line like:
username1
username3
....


Is it good practice in shell script to save such data in a file and then read the file when the data shall be used or are there better techniques? Thanks.

druuna 11-16-2012 09:30 AM

Quote:

Originally Posted by a2326 (Post 4830795)
Hello,
I want to extract all members of a group, but I don't get the output that I want:
Code:

GROUP=groupname
cat /etc/group | grep --regex "^"$GROUP":.*" | awk -F:, '{print $4}'

I would like to have an output with one user per line like:
username1
username3
....

Have a look at this:
Code:

awk -F: '/^'$GROUP'/ { gsub(/,/,"\n",$4) ; print $4 }' /etc/group
Quote:

Is it good practice in shell script to save such data in a file and then read the file when the data shall be used or are there better techniques? Thanks.
I'm not 100% sure what it is you are asking. If you are talking about saving the output of one command to use it as input for a second command then the answers is: No, try to avoid this if possible.

a2326 11-16-2012 09:48 AM

That works, thank you :-) To be more precise: Is it a good choice to store the extracted data set in a file or is better to store the data in some kind of shell script data structure? E.g., in Java or C++ you often store file data in arrays or lists and then you just loop through this data structure. However, transferring Java way of thinking to shell scripting is often not possible that's why I am asking this question.

druuna 11-16-2012 09:57 AM

Quote:

Originally Posted by a2326 (Post 4830832)
To be more precise: Is it a good choice to store the extracted data set in a file or is better to store the data in some kind of shell script data structure? E.g., in Java or C++ you often store file data in arrays or lists and then you just loop through this data structure. However, transferring Java way of thinking to shell scripting is often not possible that's why I am asking this question.

That all depends on the data and what it is you need/want to do with it (same is probably true for higher programming languages).

Bash, awk and perl (to name just 3) can use array's if needed. Do check the specific documentation, I'm sure that array's are handled differently then in Java or C(++).

These might help:

Bash resources:
Sed/Awk resources:


All times are GMT -5. The time now is 02:47 AM.