![파일의 특정 열에 특정 행을 표시하는 방법](https://linux55.com/image/37076/%ED%8C%8C%EC%9D%BC%EC%9D%98%20%ED%8A%B9%EC%A0%95%20%EC%97%B4%EC%97%90%20%ED%8A%B9%EC%A0%95%20%ED%96%89%EC%9D%84%20%ED%91%9C%EC%8B%9C%ED%95%98%EB%8A%94%20%EB%B0%A9%EB%B2%95.png)
첫째, 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