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 get some output from a command, I have to extract text between two patterns from the output. Start pattern is fixed. But the end format can be one of two (lets say word2-1 and word2-2).

Is there any way I can specify that in a single sed command?

I tried

sed -n "/Word1/,/(word2-1|word2-2)/p"
sed -n "/Word1/,/word2-1|word2-2/p"
sed -n "/Word1/,/word2-1\|word2-2/p"
sed -n "/Word1/,/[word2-1|word2-2]/p"
share|improve this question
    
The third one is correct. Show us the sample input for which not works. –  manatwork Mar 4 '13 at 8:24
    
ok. I missed a point. Sorry for that. Output can have both the end patterns, but cmd should extract till the first occurrence (does not matter which second word comes first). –  Ram Mar 4 '13 at 8:29

2 Answers 2

The regexp that matches word2-1 and word2-2 and nothing else is word2-[12]. If the suffix has more than one character, use word2-\(first\|second\) or whatever.

Your third regexp matches the same strings, just with more repetition.

share|improve this answer

Your third option works, only extracting to the first match as you stated in your comment:

$ cat > file << 'EOF'
> foo
> bar
> Word1
> foo
> bar
> word2-2
> foo
> bar
> word2-1
> EOF
$ sed -n "/Word1/,/word2-1\|word2-2/p" file
Word1
foo
bar
word2-2
share|improve this answer
    
What if file has word2-1 before word2-2 and I want to extract (word2-1/wor2-2 whichever comes first). –  Ram Mar 4 '13 at 8:31
    
@Ram That is the way that sed operates already. –  Chris Down Mar 4 '13 at 8:32
    
I am in FreeBSD and the following works fine. sed -n -E "/Word1/,/Word2-1/p" | sed -n -E "/Word1/,/Word2-2/p" Thanks for the help. –  Ram Mar 4 '13 at 8:36
1  
@Ram Capitalisation is important. –  Chris Down Mar 4 '13 at 8:44
    
@Ram, it might work fine, but also twice. –  vonbrand Mar 4 '13 at 20:04

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.