Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap 1 and 0 in the line

Tags:

vim

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?

like image 985
KarlsD Avatar asked Oct 27 '21 15:10

KarlsD


Video Answer


3 Answers

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.

like image 200
mattb Avatar answered Nov 08 '22 04:11

mattb


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
like image 39
Lieven Keersmaekers Avatar answered Nov 08 '22 06:11

Lieven Keersmaekers


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

like image 36
romainl Avatar answered Nov 08 '22 06:11

romainl