i有一个名为names.txt的文件,该文件保存了名称列表。其中一些名称与/etc/passwd(第五个字段)中的名称不对符,有些则是对应的。对于文件中的名称,这些用户具有我要打印其用户名的名称。例如,如果比尔·门(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 -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