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

Re^2: Search and replace in all odd lines

by jesuashok (Curate)
on Jun 25, 2007 at 10:52 UTC ( #623140=note: print w/ replies, xml ) Need Help??


in reply to Re: Search and replace in all odd lines
in thread Search and replace in all odd lines

perl -i.bak -nle 's/search/replace/g unless $. & 2; print' file(s)
The above will apply the changes in line numbers 1,3,5,7,......
perl -i.bak -nle 's/search/replace/g unless $. & 1; print' file(s)
The above will apply the changes in line numbers 2,4,6,8,......

NOTE: Based on the idea from Re: Search and replace in all odd lines by GrandFather


Comment on Re^2: Search and replace in all odd lines
Select or Download Code
Re^3: Search and replace in all odd lines
by johngg (Abbot) on Jun 25, 2007 at 13:36 UTC
    perl -i.bak -nle 's/search/replace/g unless $. & 2; print' file

    Your one-liner is not going to do what you think. $. & 2 is going to evaluate to true whenever the third second bit from the right (2 is binary 100) is set. Given this input file (lines.txt)

    line 1 line 2 line 3 line 4 line 5 line 6 line 7 line 8 line 9

    adapting your one-liner to just print the lines gives

    $ perl -nle 'print unless $. & 2;' lines.txt line 1 line 4 line 5 line 8 line 9

    Did you actually test your adaptation of GrandFather's idea before posting? Changing between odd and even is as simple as if $. & 1 and unless $. & 1. Perhaps you could have a look at "Bitwise And" in perlop to further your understanding.

    Cheers,

    JohnGG

    Update: Corrected typo.

    Update 2: Corrected huge balls-up, thanks fenLisesi. Where did I get "2 is binary 100" from?

    Update 3: And thanks clinton, saw your reply after /msg from fenLisesi

      you missed another typo - 2 is binary 10, not 100

      To flesh out the reasoning:

      DECIMAL BINARY TRUE / FALSE ============= ================= ============ 0 & 2 == 0 000 & 010 == 000 FALSE 1 & 2 == 0 001 & 010 == 000 FALSE 2 & 2 == 2 010 & 010 == 010 TRUE 3 & 2 == 2 011 & 010 == 010 TRUE 4 & 2 == 0 100 & 010 == 000 FALSE 5 & 2 == 0 101 & 010 == 000 FALSE 6 & 2 == 2 110 & 010 == 010 TRUE 7 & 2 == 2 111 & 010 == 010 TRUE

      Clint

        Yes, I've gone bright red :(

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (17)
As of 2014-12-19 10:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (78 votes), past polls