Reputation: 5856
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))
Upvotes: 8
Views: 4051
Reputation: 32926
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
Upvotes: 11