Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I have an output for a command as below.

Heading1
   I am one value.
   I am another value.
   I am third value. 
Heading2
   I am some value.
   I am someother value. 
   I am new value. 
Heading3

As we can see, there is a space in the beginning of the line if it is not a heading. I am trying to extract all the values under Heading1. I need the output as,

I am one value.
I am another value.
I am third value. 

If I try the command,

grep mycommand | heading1 

It gives me only the Heading1 line.

UPDATE:

I know, I have to extract the string from the starting of Heading1. But, I do not know the ending string (i.e, here I have mentioned as Heading2, but I won't be knowing it).

All I know is, I have to extract everything till the next heading which starts in a new line.

share|improve this question

3 Answers 3

Here is awk solution:

yourcommand | awk '/Heading1/ {for(n=0; n<3; n++) {getline; $1=$1; print}}'

Update

If between Heading1 and the end string only have lines start with space, you can do like this:

yourcommand | awk '/Heading1/ {flag=1;next} /^\w+/ {flag=0} {$1=$1} flag'
share|improve this answer

Roughly how to do it:

$ sed -n -e '/Heading1/,/Heading2/ p' file.txt | grep "^ " | sed 's/^[ ]\+//g'
I am one value.
I am another value.
I am third value. 

A bit more condensed version, makes use of pcregrep which allows for multiline matching:

$ pcregrep -M 'Heading1(\n|.)*Heading2' file.txt | grep "^[ ]\+"
   I am one value.
   I am another value.
   I am third value. 

To get rid of the spaces at the begining using this method, you could make use of grep's PCRE facility:

$  pcregrep -M 'Heading1(\n|.)*Heading2' a.txt | grep -oP "^[ ]{3}\K.*"
I am one value.
I am another value.
I am third value. 

Finally here's a sed and awk solution.

$ sed -n -e '/Heading1/,/Heading2/ p' file.txt | awk '/^ / {sub(/^[ ]+/, ""); print}'
I am one value.
I am another value.
I am third value. 
share|improve this answer
    
Thanks for the answer. What if I do not know the second string's name as Heading2? It can be anything and all I know is, a heading starts in that line.\ –  Ramesh Feb 8 '14 at 2:49
    
@Ramesh - do you know anything about it or not? –  slm Feb 8 '14 at 2:58
    
No, I do not know anything about the second string. All I know is the first string. –  Ramesh Feb 8 '14 at 2:59
    
I will update my question with a proper example. –  Ramesh Feb 8 '14 at 2:59

This should work:

yourcommand | grep -A3 Heading1 | grep -v Heading1
share|improve this answer
    
Explaining why that should work would be helpful... –  Potherca May 4 at 18:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.