Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim equivalent of the "tr" command

Tags:

vim

Have such line:

xxAyayyBwedCdweDmdwCkDwedBAwe
;;;; cleaner example
__A__B__C__D__C_D_BA_

want replace the ABCD into PQRT e.g. to get

__P__Q__R__T__R_T_QP_

e.g the quivalent of the next bash or perl tr

tr '[ABCD]' '[PQRT]' <<<"$string"

How to do this in "vim"? (VIM - Vi IMproved 7.4 (2013 Aug 10, compiled May 9 2014 12:12:40))

like image 792
kobame Avatar asked Sep 04 '14 12:09

kobame


1 Answers

You can use the tr() function combined with :global

:g/./call setline(line('.'), tr(getline('.'), 'ABCD', 'PQRS'))

It is easy to adapt it to a :%Tr#ABCD#PQRS command.

:command! -nargs=1 -range=1 Translate <line1>,<line2>call s:Translate(<f-args>)

function! s:Translate(repl_arg) range abort
  let sep = a:repl_arg[0]
  let fields = split(a:repl_arg, sep)
  " build the action to execute
  let cmd = a:firstline . ',' . a:lastline . 'g'.sep.'.'.sep
        \. 'call setline(".", tr(getline("."), '.string(fields[0]).','.string(fields[1]).'))'
  " echom cmd
  " and run it
  exe cmd
endfunction
like image 126
Luc Hermitte Avatar answered Sep 23 '22 00:09

Luc Hermitte