If your string contains only a single line and is composed of only 0s and 1s then you can use this
echo "111111100000000000000" |
perl -e 'while (read(STDIN, $b, 1)) { print chr(ord($b) ^ 1); } print "\n";'
If the string can contain multiple lines then just change perl -e
to perl -ne
and change the way to read the bytes (since read
needs a file handle)
echo -e "111111100000000000000\n0001111010101" |
perl -ne 'while (/(.)/g) { print chr(ord($1)^1) } print "\n"'
However that way each line is broken into a string, so it may not be very efficient for big files. In that case a little check is necessary
echo "122111111034000000000abc0000" | perl -e 'while (read(STDIN, $b, 1)) {
print ($b eq '0' or $b eq '1' ? chr(ord($b) ^ 1) : $b) } print "\n";'
As you can see, this way it also works for strings that contain characters other than '0'
and '1'