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?
5 Answers
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 1Using sed:
$ sed -n '/KFC/,/^$/p' file Restaurant: KFC City: NYC State: NY Address: 123 Madison Square Phone: 911 $ sed -n '/McDo/,/^$/p' file Restaurant: McDonalds City: Miami State: Florida Address: 123 Biscayne Blvd Phone: 911 Explanation
This is basic sed function, you can refer USEFUL ONE-LINE SCRIPTS FOR SED
# print section of file between two regular expressions (inclusive) sed -n '/Iowa/,/Montana/p' # case sensitive 2$ awk '$2=="KFC" {print; for(i=1; i<=4; i++) { getline; print}}' example.txt Restaurant: KFC City: NYC State: NY Address: 123 Madison Square Phone: 911 The above command will get and print the consecutive 4 lines along with the current line because it was fed into a for loop.The search pattern $2=="KFC" will helps to get a particular line from the multiple lines.
Another possible solution:
awk 'BEGIN{FS="\n";RS="\n\n"}{if($1=="KFC")print $0}' example.txt 1It is sufficient to print from line containing the name you want, to the last line containing word Phone ( assuming of course that all the entries follow the same pattern and will always have Phone as terminating record)
$> awk '/5 guys/,/Phone/' restaurants.txt Restaurant: 5 guys City: Atlanta State: Georgia Address: 123 Peachtree Rd Phone: 911 $> awk '/McDonalds/,/Phone/' restaurants.txt Restaurant: McDonalds City: Miami State: Florida Address: 123 Biscayne Blvd Phone: 911 If we wanted to complicate it a bit, we could print exactly 5 lines after the match, like so:
awk '/McDonalds/{stop=NR+5}; NR<=stop ' restaurants.txt Restaurant: McDonalds City: Miami State: Florida Address: 123 Biscayne Blvd Phone: 911 The stop variable will not be set, so NR<=stop will not print anything, until /McDonalds/{stop=NR+5;} part actually sets the variable, and that will only happen when we find the match.