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

Time:06-09

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 ,

#!/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 :)

CodePudding user response:

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
  • Related