Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse order of string inside brackets in vim

Tags:

vim

Is there a neat way to reverse the string inside a certain type of brackets in vim, for instance

{1,2,3,4,5}

=>

{5,4,3,2,1}

?

like image 574
Ray Hua Wu Avatar asked Jan 01 '18 00:01

Ray Hua Wu


People also ask

How to reverse all lines of input in Vim?

Source: Reverse all lines and Power of g at vim wikia. -r The -r option causes the input to be displayed in reverse order, by line. Check: man tar for more details. Show activity on this post.

How to sort text in Vim?

Sorting text in Vim is easy! Select the text, then press :, type sort, then hit enter! It'll sort the whole document by default, but you can enter a range too. Explanation on how to sort text in vim:

How do I reverse the Order of lines in a file?

Hence, you first move the first line to the top, then the second above the first, then the third above the second, etc. If you do not want to reverse the entire file, you can supply the range of lines to reverse to the command and adjust the destination accordingly.

How to move large blocks of text in reverse order?

With minor tweaking, using an actual pattern for the :g command and a range on the :m command (which could contain searches, etc.) this simple command becomes extremely versatile for moving large blocks of text and placing in reverse order. -- Fritzophrenic 14:32, January 8, 2010 (UTC)


2 Answers

How about this command?

:%s/{\zs\\(.\\{-}\\)\ze}/\= join(reverse(split(submatch(0), '\zs')), '')/g
like image 175
Rick Howe Avatar answered Sep 24 '22 12:09

Rick Howe


The idea is to utilize the append feature of register by using upper-case register name.

To achieve this, you have to do some preparations:

  • clean "a register: :let @a=""
  • add a comma before the first element: {,1,2,3,4,5}
  • put the cursor under } in normal mode

Ok, here we go:

  • execute "AdF,, and press . to repeat until all elements are deleted.
  • execute "aP to paste the reversed sequence, you will get: {,5,4,3,2,1}
  • delete the first comma
like image 42
Wray Zheng Avatar answered Sep 24 '22 12:09

Wray Zheng