Extracting text between two strings, first instance only

There are a lot of ways to extract text from between two strings, but what if those strings occur multiple times and you only want the text from the first two strings? I can't seem to find anything to work here. I'm using sed to process the text after it's extracted, so I prefer a sed answer, but whatever works is fine with me.

It's an xml file, the text is between string tags (hope that doesn't cause any confusion). The text may be 1 or 100 lines long and may also contain whitespace, linebreaks, indentions, etc, which shouldn't matter much, but the location of the tags may seem fairly random in relation to the actual text and not a clean "^tagTEXTtag$". I want everything, whitespace, blank lines, etc, between the first open and close tags.

         <string>This is
         the text 
         that I want
          
          </string>

          <string>text I don't want</string>

         <string>more text
I don't want</string>

See here or here for 2 similar examples using gawk. Use "exit" to cause a 1 instance search.

Thanks. It took me a while to figure out where to put the "exit". I'm not sure this is correct, but it works.

awk 'BEGIN{ RS="</string>"}{gsub(/.*<string>/,"")}1{print $RS;exit}' textfile

You can trim it a little: -

awk 'BEGIN{ RS="</string>"}{gsub(/.*<string>/,"");print;exit}' infile

Or you can use Perl:

$
$ cat -n f3
     1  <string>This is
     2  the text
     3  that I want
     4  ...
     5  </string>
     6
     7  <string>text I don't want</string>
     8
     9  <string>more text
    10  I don't want</string>
$
$ perl -ne 'BEGIN{undef $/} /<string>(.*?)<\/string>/s and print $1' f3
This is
the text
that I want
...
$
$

tyler_durden