Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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
share|improve this question

1 Answer 1

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
share|improve this answer
    
+1 for quick and much better answer while I was writing one with sed. Just a minor note: beginning this with cat "YourFile" | and ending with > "YourFile-Sorted" might sometimes be preferrable. –  Sadi Mar 27 at 6:59
2  
@Sadi Thank you. I have added your bash pipeline form to the answer. –  John1024 Mar 27 at 7:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.