Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

What sort command can I use to get the desired output in Linux. The sorting meth

ID: 3762338 • Letter: W

Question

What sort command can I use to get the desired output in Linux. The sorting method works, but I can't figure out how to add text, and add a new line after each colon.

This is the code I'm using that displays contents from a file "contacts.txt"

echo "Display submenue:"

echo "(1) Display all"

echo "(2) Display all sorted by Last Name"

echo "(3) Display all sorted by First Name"

echo "(4) Display all sorted by Phone Number"

echo "(5) Display all sorted by Email"

echo "(6) Return to Main Menue"

echo "Your choice?"

read choice

case $choice in

1)cat contacts.txt;;

2) echo -e "All contacts sorted by Last Name "

cat contacts.txt | head | sort -t: -k2;;

3)echo -e "All contacts sorted by First Name "

cat contacts.txt | head | sort -t: -k1;;

4)echo -e "All contacts sorted by Phone Number "

cat contacts.txt | head | sort -t: -k3;;

5) echo -e "All contacts sorted by Email "

cat contacts.txt | head | sort -t: -k5;;

6) continue;;

*) echo "invalid option"

esac

The output when choice is 3 (first name) is:

Bob:Smith:678 999 9999:141 Piedmont Ave Ne:SmithB@gmail.com

Tom:Jackson:404 555 5555:34 Peachtree St:jackson@gmail.com

The output that I want is:

First Name: Bob

Last Name: Smith

Phone Number: 678 999 9999

Address: 141 Piedmont Ave Ne

Email: smithB@gmail.com

First Name: Tom

Last Name: Jackson

Phone Number: 404 555 5555

Address: 34 peachtree st

Email: Jackson@gmail.com

Explanation / Answer

You can use below code for all the cases. I have pasted here for 2)


cat contacts.txt | head | sort -t " " -k2 > sort.txt

while read line;
do
echo "First Name: " . $line[0] . " "
echo "Last Name: " . $line[1] . " "
echo "Phone Number: " . $line[2] . " "
echo "Address: " . $line[3] . " "
echo "Email: " . $line[4] . " "
done < `cat sort.txt`

;;

Note : Try ${line[index]} if you face any problem with $line[index]

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote