sed replace all zeros with ones and all ones with zero

Viewed 172

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

2 Answers

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|.

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'
Related