您好,我需要这样做:开发一个 AWK 程序,读取/etc/passwd 并以 GID name1 name2 的形式打印具有相同 GID 的那些用户的名称。
我在 stackoverflow 上查看这篇试图开发解决方案的帖子:awk + How do I find duplicates in a column?
那里的解决方案有点管用,但不完整且格式不正确。
我在网上找到这段代码,但无法运行:
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 可以正常工作,它包含:
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.
关于linux - 用awk显示/etc/passwd中重复的GID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58424582/