Linux 使用awk在/etc/passwd中显示重复的GID

Linux 使用awk在/etc/passwd中显示重复的GID,linux,bash,unix,awk,scripting,Linux,Bash,Unix,Awk,Scripting,您好,我需要这样做:开发一个AWK程序,读取/etc/passwd并以GID name1 name2的形式打印具有相同GID的用户的名称 我在看这篇关于stackoverflow的文章,试图开发一个解决方案: 那里的解决方案有点可行,但不完整,格式不正确 我在Internet上找到此代码,但无法使其运行: awk -F: '{print $4}' /etc/passwd | sort | uniq -d > output.txt awk -F: {kount[$4]++} END{for

您好,我需要这样做:开发一个AWK程序,读取/etc/passwd并以GID name1 name2的形式打印具有相同GID的用户的名称

我在看这篇关于stackoverflow的文章,试图开发一个解决方案:

那里的解决方案有点可行,但不完整,格式不正确

我在Internet上找到此代码,但无法使其运行:

awk -F: '{print $4}' /etc/passwd | sort | uniq -d > output.txt
awk -F: {kount[$4]++}
END{for {$1 in kount[$4]}}
printf("%d %s", $4, $1) output.txt
很明显,混合使用bash和awk代码会出现一些语法问题。 我将它分为两个程序,一个bash脚本和一个awk脚本。bash one可以正常工作,它包含:

awk -F: '{print $4}' /etc/passwd | sort | uniq -d > output.txt
该程序工作正常,并给我一个文件output.txt,其中包含正确的数字65534和7

然后我尝试编写awk程序来处理该文件,结果如下:

BEGIN{ 
    FS=":" 
} 
    {a[$4]++} 

END{ 
    for {$1 in a[$4]}  
    {printf "%d %s", $4, $1}
}

这是行不通的。我觉得我真的很接近,但不能完全确定的解决方案,任何帮助将不胜感激!提前谢谢

你能试试下面的吗

awk -F':' '{a[$4]=(a[$4]?a[$4] OFS:"")$1;b[$4]++} END{for(i in a){if(b[i]>1){print i,a[i]}}}' Input_file
这将给出gid,然后给出一行中具有相同gid值(未测试)的所有用户

解释:为上述代码添加解释

awk -F':' '                           ##Starting awk program here and setting field separator as colon here.
{
  a[$4]=(a[$4]?a[$4] OFS:"")$1        ##Creating an array named a whose index is $4 and its value is $1 which will be keep concatenating itself on each occurrence.
}
END{
  for(i in a){                        ##Starting a for loop to traverse through all items of array a here.
    print i,a[i]                      ##Printing index is array a current element along with its value.
  }                                   ##Closing for loop BLOCK here.
}
' Input_file                          ##Mentioning Input_file name here.

如果您没有绑定到awk,并且可以使用不需要子shell的纯bash解决方案:

#!/bin/bash

while IFS=: read name pw uid gid remain; do
  [ "${gid}" != "" ] && groups[${gid}]+="${name} "
done < /etc/passwd

for gid in ${!groups[@]}; do
  echo "${gid}: ${groups[${gid}]}"
done

@Ratchetfan775,很高兴它帮助了你,干杯,很高兴在这个伟大的网站上学习。
0: root sync shutdown halt operator 
1: bin 
2: daemon 
4: adm 
7: lp 
...