繁体   English   中英

从/ etc / passwd中提取相应的信息

[英]Pull out corresponding info from /etc/passwd

我有一个名为names.txt的文件,其中包含名称列表。 其中一些名称与/ etc / passwd(第5个字段)中的名称不对应,而有些则与。 对于文件中具有用户名的名称,我要打印其用户名。 例如,如果名称Bill Gates在names.txt文件中,而该行在/etc/passwd bgates:x:23246:879:Bill Gates:/co/bgates:/bin/bash我将打印出“ Bill Gates存在,并且用户名“ bgates””

这是我一直在尝试的方法,但是它只是打印出整个/ etc / passwd文件。

while read name; do

if cut -d: -f5 '/etc/passwd' | grep -q "$name"; then
        userName=$(cat /etc/passwd | cut -d: -f6)
        echo "$name exists and has the username $userName"
else
        echo "no such person '$line'"
fi
done < names.txt

谢谢

也许是这样的吗?

#!/bin/bash

#set -x
set -eu
set -o pipefail

function get_pwent_by_name
{
    full_name="$1"
    while read pwent
    do
        pw_full_name=$(echo "$pwent" | awk -F':' ' { print $5 }')
        if echo "$pw_full_name" | egrep -iq "$full_name"
        then
            echo "$pwent"
            break
        fi
    done < /etc/passwd
}

while read name
do
    pwent=$(get_pwent_by_name "$name")
    if [ "$pwent" != "" ]
    then
        userName=$(echo "$pwent" | awk -F':' ' { print $1 }')
        echo "$name exists and has the username $userName"
    else
        echo "No such person as $name"
    fi
done < names.txt

您接受使用awk解决问题吗?

awk -F: 'NR==FNR{a[$5]=$1;next} 
         {print ($0 in a)?$0 " exists and has the username " a[$0]:"no such person " $0}' /etc/passwd names.txt

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM