Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^2: Search and replace in all odd lines

by jesuashok (Curate)
on Jun 25, 2007 at 10:52 UTC ( [id://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

Replies are listed 'Best First'.
Re^3: Search and replace in all odd lines
by johngg (Canon) 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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://623140]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2024-04-24 08:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found