Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

One liner to subtract by 2

by dirtdog (Monk)
on Jul 24, 2013 at 14:02 UTC ( #1046121=perlquestion: print w/replies, xml ) Need Help??
dirtdog has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I'm trying to figure out how to use a one liner to search & replace a header count. For example, the following line is the header:


The Last 10 digits are always the record count. In this example the record count is 0000000496 or 496.

Is it possible to use a one liner to subtract by 2 to make the count 0000000494?

I should also add the count will be different every day

Any help would be greatly appreciated.


Replies are listed 'Best First'.
Re: One liner to subtract by 2
by choroba (Bishop) on Jul 24, 2013 at 14:05 UTC
    You can use the /e switch of the substitution operator:
    perl -pe 's/([0-9]{10})$/sprintf "%010d",$1-2/e'

    Update: I am not sure how to search for the line, though, because you did not give any information on how these lines are structured. Adding that to the one-liner is easy, e.g. let's pretend we want to process lines beginning with 0TONY:

    perl -pe 's/([0-9]{10})$/sprintf "%010d",$1-2/e if /^0TONY/'

    Update 2: sprintf added. Thanks derby.

    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      You'll lose leading zeros with that.


      update: so perl -pe 's/([0-9]{10})$/sprintf("%010d", $1-2)/e'

        Thanks, fixed.
        لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: One liner to subtract by 2
by rjt (Deacon) on Jul 24, 2013 at 14:08 UTC
    echo 0TONYHLDGS201307240901201307240000000496 | perl -pe 's/(\d{10})$/sprintf("%01 0d",$1-2)/e'
Re: One liner to subtract by 2
by hdb (Monsignor) on Jul 24, 2013 at 14:34 UTC

    perl -pe "s/(\d{10})$/substr $1+9_999_999_998,-10/e"
Re: One liner to subtract by 2
by dirtdog (Monk) on Jul 24, 2013 at 14:52 UTC

    thanks all...this worked perfectly

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1046121]
Front-paged by Arunbear
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (7)
As of 2018-05-24 10:32 GMT
Find Nodes?
    Voting Booth?