首先,我不允许使用 awk、sed 或 perl。
对于我的任务,我收到了一份员工名单文件:
Marketing Ranjit Singh FULLEagles Dean Johnson
Marketing Ken Whillans FULLEagles Karen Thompson
Sales Peter RobertsonPARTGolden TigersRich Gardener
President Sandeep Jain CONTWimps Ken Whillans
Operations John Thompson PARTHawks Cher
Operations Cher CONTVegans Karen Patel
Sales John Jacobs FULLHawks Davinder Singh
Finance Dean Johnson FULLVegans Sandeep Jain
EngineeringKaren Thompson PARTVegans John Thompson
IT Rich Gardener FULLGolden TigersPeter Robertson
IT Karen Patel FULLWimps Ranjit Singh
长话短说,系统会提示用户提供名称或名称的一部分,并且仅在第二“列”中搜索该单词。如果在那里找到,则询问用户是否想要该人的团队名称(第三列,“部分”或“完整”等旁边的单词)或该人的搭档(最后一列)。
最终结果只是在团队名称或合作伙伴旁边显示全名。
我无法弄清楚最后一步......仅剪切与原始搜索匹配的行并仅显示所需的“列”。
while :
do
echo Enter the name of the player you want to search for:
read name
if (cut -c12-26 emplist | grep -n ${name} > namefile)
then
while :
do
echo 'See partner (P/p) or team name (T/t)?'
read answer
if [ ${answer} = "T" -o ${answer} = "t" ]
then
**#Steps for showing only the full name and the team name**
break
elif [ ${answer} = "P" -o ${answer} = "p" ]
then
**#Steps for showing only the full name and the partner name**
break
else
echo Please enter only T or M.
fi
done
elif [ ${name} = "ZZZ" ]
then
break
else
echo Name not found.
fi
done
答案1
您可以执行类似的操作(此处用于搜索John
和报告团队):
$ cut -c12-26 <emplist | paste -d: - emplist | grep '^[^:]*John' | cut -c1-16,47-59
John Thompson :Hawks
John Jacobs :Hawks
Dean Johnson :Vegans
答案2
Stephane 已经为您提供了一种使用方法cut
,但如果您想纯粹在 bash 中执行此操作,您可以尝试以下操作:
#!/usr/bin/env bash
## Declare the associative arrays that will
## hold your data
declare -A partner;
declare -A team;
## Read the data
while IFS= read line
do
## Extract the relevant column
fullname="${line:11:15}"
## save the other columns in their arrays
partner["$fullname"]="${line:43}"
team["$fullname"]="${line:30:13}"
done < emplist
echo "Enter the name of the player you want to search for:"
read name
## Check that the name exists or exit
if ! grep -q "$name" emplist
then
echo "Name not found"
exit
fi
## Read what we're after
while true;
do
echo "See partner (P/p) or team name (T/t)?"
read answer
case $answer in
[tTpP])
break
;;
*)
echo "Please enter only T or M."
esac
done
## Now go through each of the names in the
## second column and check if they match the
## name requested.
for fullname in "${!partner[@]}"
do
if [[ $fullname =~ $name ]];
then
case $answer in
[tT])
printf "%s\t%s\n" "$fullname" "${team[$fullname]}"
;;
[pP])
printf "%s\t%s\n" "$fullname" "${partner[$fullname]}"
;;
esac
fi
done