Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

AWK / SCRIPT , return number of values from specific field in the /etc/group file

Im trying to write somthing that will give me this type of output using awk.

I’m trying to extract the group name , the group ID and the numbers of users in each group from the /etc/group file

Group : root    ID:0 : 2 accounts 

Group : daemon  ID:  1  : 1 account

Group : bin  ID:  2  : 1 account

Ive tried this for now ,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#!/bin/bash    
NbrsUtil=$(cut -d ":" -f4 /etc/group | awk -F "," '{print NF}')



awk -v utils=$NbrsUtil  -F ":"  '{print "Groupe:",$1,"ID:" $3,utils," :accounts"} ' /etc/group 

This is not working ..
i can try to use "cut" to specify the field i want , and then I use awk to count the number of fiels via the "|" , and i get the good values but the output is not good and does not work with my script.

cut -d ":" -f4 /etc/group | awk -F "," '{print NF}'
0
0
0
0
2
0
0
0
0
0
0
0
0
0
2
0

If i echo the command in the script it show in one line

#!/bin/bash

NbrsUtil=$(cut -d ":" -f4 /etc/group | awk -F "," '{print NF}')
echo $NbrsUtil
awk   -F ":"  '{print "Groupe:",$1,"ID:" $3,$4," :accounts"} ' /etc/group 

–>

0 0 0 0 2 0 0 0 0 0 0 0 0 0 2 0 0 1 1 0 1 2 1 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 2 0 0 1 0 0 0 1 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 2 0 0 0 0
Groupe: root ID:0  :accounts
Groupe: daemon ID:1  :accounts
Groupe: bin ID:2 :accounts
Groupe: sys ID:3 :accounts
Groupe: adm ID:4 franco,root :accounts
Groupe: tty ID:5 :accounts
Groupe: disk ID:6 :accounts
Groupe: lp ID:7 :accounts
Groupe: mail ID:8 :accounts

Any help will be greatly appreciated 🙂

>Solution :

awk has a split function that can help:

split(s, a[, fs ])
Split the string s into array elements a[1], a[2], …, a[n], and return n. […] The separation shall be done with the ERE fs or with the field separator FS if fs is not given.

So you can just do:

awk -F: '{print "Group:",$1,"ID:",$3,"Accounts:",split($4,_,",")}' /etc/group
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading