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"
  • 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

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.


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
$ sed -n "/Word1/,/word2-1\|word2-2/p" file
  • 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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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