curious
curious

Reputation: 710

sed replace all zeros with ones and all ones with zero

have this: 0|1 1|1 0|0 1|0 .|1 0|.

want this: 1|0 0|0 1|1 0|1 .|0 1|.

I was thinking this would work: sed -e 's/0/1/g' -e 's/1/0/g'

but just seems to give me all zeros

Upvotes: 2

Views: 455

Answers (2)

Benjamin W.
Benjamin W.

Reputation: 52112

There is a slightly lesser-known sed command to transliterate, y, which comes in handy here:

$ sed 'y/01/10/' <<< '0|1    1|1    0|0    1|0    .|1    0|.'
1|0    0|0    1|1    0|1    .|0    1|.

Upvotes: 6

Mike Slinn
Mike Slinn

Reputation: 8403

Let's play computer.

Given this:

0|1 1|1 0|0 1|0 .|1 0|.

... change all 0s to 1s. Now you have this:

1|1 1|1 1|1 1|1 .|1 1|.

... OK, now you are stuck. There are only 1s left and you do not know which to change back.

... so instead change the 0s into 2s, just for a brief moment:

2|1 1|1 2|2 1|2 .|1 2|.

... now change the 1s to 0s

2|0 0|0 2|2 0|2 .|1 2|.

... and then the 2s to 1s

1|0 0|0 1|1 0|1 .|1 1|.

And now the grand finale:

$ sed -e 's/0/2/g' -e 's/1/0/g' -e 's/2/1/g'

Upvotes: 1

Related Questions