Wednesday, April 13, 2022

[SOLVED] Shell Script - Getting lines printed between pattern based on input number

Issue

I found many examples related to printing lines between two patterns via shell script. However, I came up with a situation on printing lines between blocks based on given input number. So, this is basically a tex file with 100s of Questions written. Here is my sample input file:

StartQuestion     # First Question Block  
\item This is First Question. 
A) Answer-1
B) Answer-2
C) Answer-3
D) Answer-4
EndQuestion
StartQuestion     # Second Question Block
\item This is Second Question.
A) Answer-1
B) Answer-2
C) Answer-3
D) Answer-4
EndQuestion

StartQuestion     # Third Question Block
\item This is Third Question.
A) Answer-1
B) Answer-2
C) Answer-3
D) Answer-4
EndQuestion

StartQuestion     # Fourth Question Block
\item This is Fourth Question.
A) Answer-1
B) Answer-2
C) Answer-3
D) Answer-4
EndQuestion
StartQuestion     # Fifth Question Block
\item Why are we studying Linear Momentum?
EndQuestion

..... and so on.

So every block starts with StartQuestion and ends with EndQuestion tag. I am able to get all the questions between the blocks using sed. I feel this is more generic for my case.
However, if a user asks to print Questions 3, 4 and 32 only, how may I extract lines between blocks 3, 4 and 32 using bash ? can someone please support me on this ?


Solution

You could use awk instead.

Increment a counter when each block starts - and then test before printing inside the block.

$ awk '/StartQuestion/{ n++ } /StartQuestion/,/EndQuestion/{ if (n == 1 || n == 3) print }' questions.txt
StartQuestion     # First Question Block  
\item This is First Question. 
A) Answer-1
B) Answer-2
C) Answer-3
D) Answer-4
EndQuestion
StartQuestion     # Third Question Block
\item This is Third Question.
A) Answer-1
B) Answer-2
C) Answer-3
D) Answer-4
EndQuestion


Answered By - user15398259
Answer Checked By - Mary Flores (WPSolving Volunteer)