For the very first time I find myself in need for the y command Sed has.
For those who don't know what y does, here's an example:
$ echo x1 x2 x3 | sed 'y/123/234/'
x2 x3 x4
Apparently Vim has no way of doing this. Am I wrong?
Sure it does. In unix there's often a command equivalent to sed y/X/x/ called tr. So...
echo "A1B2C3" | sed 'y/ABC/abc/' # prints "a1b2c3"
...is equivalent to...
echo "A1B2C3" | tr 'ABC' 'abc' # also print "a1b2c3"
It happens that Vim has a function that is "exactly like the unix 'tr' command": :h tr()
So...
:echo tr("A1B2C3", "ABC", "abc")
That will print, of course, "a1b2c3".
BLayer’s answer nicely covers the vimscript equivalent for programming.
For completeness, you can also perform these operations on a buffer:
:[range]!sed … or :[range]!tr … (this is often easier to type with the normal-mode ! operator, which prefills the :[range]!):[range]substitute/[charset1]\+/\=tr(submatch(0), charset1, charset2)/There’s a version of the last with a dictionary, but it’s slightly less readable to my eyes. Unfortunately both require you to repeat the starting set of characters, unless you use the pattern .\+ (which may be slower, as vim will consider every character of every line, rather than batching groups to be translated; benchmark if it matters to you).
You can pipe a line, or any selection of lines through a UNIX command.
So in your example, position your cursor on the line you wish to modify, and then type ":" to get into edit/command mode and add a ".|" meaning pipe the current line though a command, and then type your command.
:.| sed 'y/123/234/'
This is an amazing capability, you can designate a range of line, or pattern match lines as well of course.
.! instead of .|. Also note that this information is covered in my answer.
– D. Ben Knoble
Jul 08 '21 at 20:30