Hi I'm working with bash script and I have example.txt below. How can I alphabetize the following 4 information about restaurants by the restaurant name and print it out? Note that the format when printed alphabetically that it should remain the same as below including city, state, address, phone.
Restaurant: McDonalds City: Miami State: Florida Address: 123 Biscayne Blvd Phone: 91341 Restaurant: Five guys City: Atlanta State: Georgia Address: 123 Peachtree Rd Phone: 9234211 Restaurant: KFC City: NYC State: NY Address: 123 Madison Square Phone: 95311 Restaurant: Taco Bell City: LA State: CA Address: 123 Rodeo Drive Phone: 911 1 Answer
Here is a solution using awk:
$ awk 'BEGIN{FS="\n";RS=""} {r[$1]=$0} END{n = asort(r); for (i=1;i<=n;i++){print r[i] "\n"}}' restaurants Restaurant: Five guys City: Atlanta State: Georgia Address: 123 Peachtree Rd Phone: 9234211 Restaurant: KFC City: NYC State: NY Address: 123 Madison Square Phone: 95311 Restaurant: McDonalds City: Miami State: Florida Address: 123 Biscayne Blvd Phone: 91341 Restaurant: Taco Bell City: LA State: CA Address: 123 Rodeo Drive Phone: 911 awk reads in the file one record at a time. We define the record separator, RS, to be "" so that records are separated by a blank line. All the records are read into an array r. At the end, the array r is sorted and printed.
As @Sadi points out in the comments, the awk command is adaptable to use in a pipeline:
cat restaurants | awk 'BEGIN{FS="\n";RS=""} {r[$1]=$0} END{n = asort(r); for (i=1;i<=n;i++){print r[i] "\n"}}' >sorted_list_of_restaurants 2