3

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?

3 Answers 3

11

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".

2
  • 4
    I think you can be promoted to A Layer, if B is a ranking :P
    – Enlico
    Jul 5, 2021 at 9:53
  • LOL. First time I've heard that one. Thanks for the compliment. ;)
    – B Layer
    Jul 5, 2021 at 9:53
6

BLayer’s answer nicely covers the vimscript equivalent for programming.

For completeness, you can also perform these operations on a buffer:

  • on a *nix, :[range]!sed … or :[range]!tr … (this is often easier to type with the normal-mode ! operator, which prefills the :[range]!)
  • entirely portably, :[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).

0
0

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.

1
  • 1
    You might want to edit with a particular eye towards formatting. I do believe you meant type .! instead of .|. Also note that this information is covered in my answer.
    – D. Ben Knoble
    Jul 8, 2021 at 20:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.