我有一个名为names.txt的文件,其中包含一个名称列表。其中一些名称与/ etc / passwd(第5个字段)中的名称不对应,而某些名称则与。对于文件中具有名称的用户的名称,我要打印其用户名。例如,如果名称比尔盖茨在names.txt文件中并且此行在/etc/passwd bgates:x:23246:879:Bill Gates:/co/bgates:/bin/bash
中,我会打印出“比尔盖茨存在且用户名为'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
谢谢
答案 0 :(得分:3)
也许是这样的?
#!/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
答案 1 :(得分:2)
你接受使用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