簡體   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