'How to print everything between two patterns using awk

I can print everything between two patterns with this awk command:

awk '/'$1'/{a=1} a; /PATTERN2/{a=0}' ~/the/path/to/file.txt

What I need is to print everything between and include PATTERN1 and everything before PATTERN2 (which is always a line that starts with #.

Actually the patterns are hashtags like #france and #germany.

For example the file contains:

#france
France is a European country.
It's capital city is Paris.
One of its biggest cities is Lyon.

#germany
Germany is a European country.
It's capital city is Berlin.
One of its biggest cities is Munich.

What I want to be printed after calling #france:

#france
France is a European country.
It's capital city is Paris.
One of its biggest cities is Lyon.

Also it would be great if I can show the pattern in another color like blue or red.

awk


Solution 1:[1]

If there is always blank line between entries you might harness paragraph mode of GNU AWK by setting RS to empty string, let file.txt content be

#france
France is a European country.
It's capital city is Paris.
One of its biggest cities is Lyon.

#germany
Germany is a European country.
It's capital city is Berlin.
One of its biggest cities is Munich.

then

awk 'BEGIN{RS=""}/^#france/' file.txt

output

#france
France is a European country.
It's capital city is Paris.
One of its biggest cities is Lyon.

Explanation: RS="" causes GNU AWK to treat paragraphs as rows. I simply filter rows which starts with (^) #france.

(tested in GNU Awk 5.0.1)

Solution 2:[2]

With your shown samples only, you can try following awk code. Where I am using RS(record separator) as paragraph mode and checking if line starts from particular string then print that whole para.

awk -v RS="" '$0~/^#france\n/' Input_file

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daweo
Solution 2 RavinderSingh13