[英]Pull out corresponding info from /etc/passwd
I have a file called names.txt that holds a list of names. 我有一个名为names.txt的文件,其中包含名称列表。 Some of these names do not correspond to names in /etc/passwd (5th field) and some do. 其中一些名称与/ etc / passwd(第5个字段)中的名称不对应,而有些则与。 For the names in the file that have users with the name I want to print their user name. 对于文件中具有用户名的名称,我要打印其用户名。 For example if the name Bill Gates was in the names.txt file and this line is in /etc/passwd bgates:x:23246:879:Bill Gates:/co/bgates:/bin/bash
I would print out "Bill Gates exists and has the username 'bgates'" 例如,如果名称Bill Gates在names.txt文件中,而该行在/etc/passwd bgates:x:23246:879:Bill Gates:/co/bgates:/bin/bash
我将打印出“ Bill Gates存在,并且用户名“ bgates””
This is what I've been trying, but it just prints out the entire /etc/passwd file. 这是我一直在尝试的方法,但是它只是打印出整个/ 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
Thank you 谢谢
Maybe something like this? 也许是这样的吗?
#!/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
Do you accept to use awk to resolve your problem? 您接受使用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.