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.

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?

share|improve this question

3 Answers 3

up vote 5 down vote accepted

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
share|improve this answer
$ 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.

share|improve this answer

Using 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

1) this is basic sed function, you can refer USEFUL ONE-LINE SCRIPTS FOR SED http://sed.sourceforge.net/sed1line.txt

 # print section of file between two regular expressions (inclusive)
 sed -n '/Iowa/,/Montana/p'             # case sensitive
share|improve this answer
    
Add the explanation. –  BMW Mar 27 at 4:36

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.