A one-liner using the in-place edit switch.

perl -pi.bak -e 's/^[^"]*"([^"]+?)"[^"]*$/$1/' filename

This reads in the line, and drops everything that comes before the first quote, or after the second. It will fail if the string contains more than one set of balanced quotes. It then writes the part that came between the quotes back out to the original file, and leaves a backup in place.

That's a slight lie, actually; If I recall -i.bak semantics, it renames the input file, and then writes a new file to the original input filename.

You can mimic that approach in long-hand code as well; open the input file, rename it to something else to save it just in case, open a new output file to the name of the old input file, read each line, drop the parts you don't want, write each line out to the output file, done.

But problems where you're matching text between quotes are seldom as simple as they seem at first. What if the string is, This is line 1 "Hello! I said, "Hello!""? Now you've got a problem. That problem is handled more easily using Text::Balanced.


Dave


In reply to Re: Regex: Changing $1 by davido
in thread Regex: Changing $1 by packetstormer

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.