I was asked to solve a problem at work so I tried to make it as short possible.

Problem:

Read and Modify a file in place containing lines in the format of "variable = number" taking into consideration any whitespace around the equal sign.

Example input:

one=1 two=2 three=3 xyz=20

Increment the value of a specific variable in the file and write it back out.

Ex: where variable is xyz.

one=1 two=2 three=3 xyz=21

My attempt:

where xyz is the variable whose value is being incremented by 1 and test.data is the file containing data.

perl -p -i.bak -e 's/$1/$a/ if ((/xyz\s*=\s*([0-9]*)\s*/)&&($a=$1+1))' + test.data
-mlm

In reply to Can anyone make this shorter? by mlm

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.