Grep utility - quick one!

Hi all,

Quick question related to Grep.

I would like to capture only the questions from a file.

-----example------
QUESTION 2 Which four are …end? (Choose four)
A. Answer1 B. answer2 C. answer3 D. answer4 E. answer5 F. answer6
Answer: A,B,C,E

QUESTION 3 What is the …end?
A. 4 groups B. 13 groups C. 24 groups D. 64 groups E. 128 groups
Answer: D
------------end--------------

I would like to ‘capture’ and export only the QUESTIONS to a file.

My output will look like:

–file.txt–
Which four are …end? (Choose four)
What is the …end?
----end----

Is it possible to grep anything between QUESTION xx(space) and A.?

Is it possible to grep all ANSWERS
Exemple GREP anything between A. and B.
Exemple GREP anything between B. and C.

Thanks!

Not sure about grep but as you have clearly defined fields I suspect it maybe made better for awk. But in playing I thought why not use cut so

grep QUESTION | cut -d" " -f3-

All answers look at egrep and using ^A. regex I think this should do it.

Hi

This seems a task for sed … :slight_smile:

sed -e '/QUESTION/ !d' -e 's/^ *QUESTION [0-9]* *//' <file >outfile

Code not tested, but I’m confident.

Did you read man grep?
I ask because if I understand correct what you have written, you do not understand quite what grep is doing. It chooses lines from a fiile and rejects others. So when you grep on ‘QUESTION’, you will get as output only the lines containing the string QUESTION, but not parts of those lines. When you want parts of those line, you can start with grep to select the lines and then pipe to other tools like sed, etc. (like suggested above by others). Something like:

grep 'QUESTION' inputfile | sed -e 's/QUESTION//' -e 's/?//'

These sort of tasks require a combination of tools. I recommend to study at least the man pages of grep, sed, tr, cut and regular expresssions.

not quite true, if using awk, no need to combine tools.


awk '/QUESTION/{$1=$2="";print}' file

@ghostdog74
You are correct, but awk is not anybodies tool (but learning it is not a bad idea) and what I tried to show to the OP is that you should split up your task in logical parts and that Unix/Linux then offers you the primitives (tools) that can do each of those tasks (task1 selecting lines, task2 replacing strings with empty ones) and that piping is a strong mechanism in combining these.

But again, you are correct and in your awk example one sees both tasks also in the right sequence: first select, then change strings.