bashunixetcpasswd

I am traying to substitute group name for group number in UNIX


I have to write skrypt which will show file /etc/passwd in that why GroupID will be exchange by by GroupName

I have two files which looks like:

-> /etc/passwd structure : UserName:x:UserID:GroupID:description:homeFile:DefaultInterpreter

-> /etc/group structure : GroupName:x:GroupID:AdditionalUsers


Solution

  • You can do this with awk processing both /etc/group and /etc/passwd

    awk -F: 'NR==FNR { grp[$3]=$1 } NR != FNR { OFS=":";$4=grp[$4] }1' /etc/group /etc/passwd
    

    Set the field delimiter to : and then read the /etc/group file (NR==FNR). Create an array grp indexed by the group ID with the group name as the contents for each entry. Then process /etc/passwd (NR!=FNR). For each line, get the group ID (4th delimited field) and substitute it with the content of grp[$4], setting the output field separator (OFS) accordingly. Use 1 to print the amended line.