Ubuntu – How to process multi-line records with awk in a bash script

awkscripts

example.txt is below

Restaurant: McDonalds 
City: Miami
State: Florida
Address: 123 Biscayne Blvd
Phone: 911

Restaurant: 5 guys
City: Atlanta
State: Georgia
Address: 123 Peachtree Rd
Phone: 911

Restaurant: KFC
City: NYC
State: NY
Address: 123 Madison Square
Phone: 911

Im using bash script and lets say I want to search for a restaurant by its name from the file above. Ask the user input for the restaurant name and it should print the information regarding that restaurant (5 lines).

awk '/McDonalds/> /KFC/' example.txt

I know that line of code above will print the whole line that matches the pattern "McDonalds" and "KFC" but that will just print the 1st line from the text file but not the rest of the information about that restaurant. How can I tell it to print all of the information (5lines) from just the user input of the restaurant name?

Best Answer

With awk, you can change the record separator. By default it is a newline, so each line of the file is a record. If you set the RS variable to the empty string, awk will consider records to be separated by blank lines:

awk -v name="KFC" -v RS="" '$0 ~ "Restaurant: " name' example.txt
Related Question