I have the following line:
0110101010
It is necessary to convert 1 to 0, and 0 to 1, i.e. to get:
1001010101
Is there any way to do this with vim?
How about just using a temporary variable:
:s/0/x/g | s/1/0/g | s/x/1/g
The |
allows multiple commands to be executed in sequence (see :help :command-bar
).
So we first change 0
to x
(so we don't end up with all zeros with the 2nd
command), then change 1
to 0
, and finally change the x
(which were
formerly 0
) to 1
.
You can use the matches to apply some logic to it in your replace statement
:s/\v(0|1)/\=submatch(0)==0?1:0/g
Breaks down to
\v(0|1) search for either a 0 or 1
\=submatch(0)==0?1:0 if match equals 0 replace with 1, otherwise with 0
Look for :h \=
and :h submatch
for additional help.
Edit cudo's to BEn C
alternatively, use some clever arithmetic to shorten the command
:s/\v(0|1)/\=1-submatch(0)/g
How about leveraging common command-line tools?
:.!tr 10 01
Or a purely programmatic approach?
:call getline('.')->tr('01','10')->setline('.')
See :help getline()
, :help setline()
, :help tr()
, and :help :!
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With