How can I process multi-line records with awk in a bash script?
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
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
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
$ 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.