What is the quickest way of replacing 0 by 1 and vice-versa in a stream?
You can use tr
for this, its main purpose is character translation:
echo 111111100000000000000 | tr 01 10
Your sed
command replaces all 0s with 1s, resulting in a string containing only 1s (the original 1s and all the replaced 0s), and then replaces all 1s with 0s, resulting in a string containing only 0s.
On long streams, tr
is faster than sed
; for a 100MiB file:
$ time tr 10 01 < bigfileof01s > /dev/null
tr 10 01 < bigfileof01s > /dev/null 0.07s user 0.03s system 98% cpu 0.100 total
$ time sed y/10/01/ < bigfileof01s > /dev/null
sed y/10/01/ < bigfileof01s > /dev/null 3.91s user 0.11s system 99% cpu 4.036 total
Although tr
is the right tool for this job you can do it in sed
using the y
(transliteration) command rather than the s
(substitution) command:
$ echo '111111100000000000000' | sed 'y/01/10/'
000000011111111111111
y
is basically sed
's internal implementation of tr
- with all the overhead that implies.
A way is echo "111111100000000000000" | sed 's/1/2/g;s/0/1/g;s/2/0/g'