Output block of lines in a file based on grep result

Hi I would appreciate your help with this.
I have a output file from a command. It is broken based on initial of the users. Exmaple of iitials MN & SS. Under each section there is information pertaining to the user however each section can have different number of lines. MY challenge is to
Grep for a particular initials ( Example MN ) and print all the lines under this initial
and put them in to a new file. The problem is that uder each initial there could be any number of lines. So the number of lines per initial is not fixed. How can I do this? I put sample of input and output files.

Input File name >> myfile.txt
Content of the file

MN
11
22
33

SS
11
22
33
44

MN
44
55

SS
55
66
77
OUTPUT File >> Should look like this

MN
11
22
33

MN
44
55

How about this, using awk:

awk '$1=="MN"' ORS="\n\n" RS= infile
1 Like

Thanks! Worked like a charm
I need to figure out what these options do
so I can use it again

RS is record separator, when it is blank an empty line is used a the record separator ORS it the output record separator "\n\n" causes the output to also have a blank line (two newline chars) between records

Hi All,

Can anyone please let me know how to achieve the below output.
My input file is like :

[Name1]
Address=abc
mob=1234

[Name2]
Address=bcd
mob=5678

Now from command line i need to supply [Name1] or [Name2] and according to that my i want the output. That means if input is [Name1] than output will be :
Address=abc
mob=1234

I have used the below commands :
awk '$1=="[Name1]"' ORS="\n\n" RS= input_file.txt

But when i am trying the below mentioned steps than I am not getting the output.
#!/bin/sh

value=Name1
name1_addr=`awk '$1=="[$value]"' ORS="\n\n" RS= input_file.txt|grep "^Address"|cut -d'=' -f2`
echo $name1_addr

Can anyone help me to resolve this issue ?

Thanks,
Monu

---------- Post updated 06-30-13 at 12:25 AM ---------- Previous update was 06-29-13 at 11:45 PM ----------

I have got the answer to my above question.

A general solution with a state variable

awk '$1~/^\[/ {s=0} s==1 {print} $1=="["key"]" {s=1}' key="$value" input_file.txt

One can simply add a sub key

awk -F= '/^\[/ {s=0} s==1 && $1==subkey {print $2} $0=="["key"]" {s=1}' key="$value" subkey="Address" input_file.txt