【问题标题】:Show duplicate GID in /etc/passwd with awk使用 awk 在 /etc/passwd 中显示重复的 GID
【发布时间】:2023-04-04 13:10:01
【问题描述】:

您好,我需要这样做:开发一个 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

该程序正常运行,并为我提供了一个包含正确数字 65534 和 7 的文件 output.txt。

然后我尝试编写 awk 程序来处理该文件,它看起来像这样:

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

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

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

【问题讨论】:

    标签: linux bash unix awk scripting


    【解决方案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.
    

    【讨论】:

    • @Ratchetfan775,很高兴它对您有所帮助,在这个伟大的网站上欢呼并快乐学习。
    【解决方案2】:

    如果您不依赖于 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
    

    样本输出:

    0: root sync shutdown halt operator 
    1: bin 
    2: daemon 
    4: adm 
    7: lp 
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 2020-07-07
      相关资源
      最近更新 更多