Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: String Search/Replace

by ChrisR (Hermit)
on Aug 31, 2005 at 15:07 UTC ( [id://488133]=note: print w/replies, xml ) Need Help??


in reply to String Search/Replace

How about a regex:
#!c:\perl\bin\perl.exe -w use strict; use warnings; for my $line (<DATA>) { $line =~ s/ \d{4,}( |$)/ 0$1/g; print $line; } __DATA__ 1125356700 0 0 0 0 1125356400 15 0 25 0 1125356100 25 0 25 0 1125355800 25 0 25 0 1125355500 25 0 25 0 1125397800 0 0 0 0 1125397500 0 0 0 0 1125397200 0 0 0 0 1125396900 0 0 0 0 1125396600 0 0 0 0 1125396300 0 0 0 0 1125396000 39006 0 63597 0 1125395700 63597 0 63597 0 1125395400 63597 0 63597 0 1125395100 63597 0 63597 0 1125394800 63597 0 63597 0 1125394500 63597 0 63597 0 1125394200 63597 0 63597 0

Or for a one liner:

perl.exe -ple "s/ \d{4,}( |$)/ 0$1/g" filename

Update:

Oops... As cheseter has pointed out, the above will replace 1000 when it should not.

Here's my regex that works:

$line =~ s/ (\d+)/$1>1000?" 0":" $1"/ge;
or at least I think it does.

Replies are listed 'Best First'.
Re^2: String Search/Replace
by ikegami (Patriarch) on Aug 31, 2005 at 15:33 UTC

    {4,} is greedy, so the ( |$) is not needed. The following is sufficient, shorter and faster:

    perl -ple "s/ \d{4,}/ 0/g" infile >outfile
      Thanks. I didn't think about that. I've never been very good at golf (perl or otherwise).
      The -l is unnecessary, too.

      Caution: Contents may have been coded under pressure.
Re^2: String Search/Replace
by chester (Hermit) on Aug 31, 2005 at 16:03 UTC
    Actually doesn't the original question say to replace numbers "over 1000" with 0? Your solution also replaces 1000 with 0, which would be incorrect.
      Err... You've got me there. I think you should remove the strike from your previous post. Your solution is the shortest since it appears that mine is incorrect.
Re^2: String Search/Replace
by gargle (Chaplain) on Aug 31, 2005 at 18:38 UTC

    Hi,

    I really do love regex's but sometimes, when only used to cut up a string in pieces, pieces seperated by the same character, I prefer to use split. Reading the code becomes a bit easier on the eyes because you can immediately deduct the meaning of the line of code. With regex's you still have to do a bit of mental juggling before the intention becomes clear.

    --
    if ( 1 ) { $postman->ring() for (1..2); }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://488133]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (2)
As of 2024-04-19 20:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found