1

I use vim on the command line. I want to use the substitution command to search for and replace characters in the command line I’m currently working on in the CLI.

Here’s merely one example, say I want to rename a file and begin writing a command like so:

mv here_is_a_way_too_long_filename.txt here_is_a_way_too_long_filename.txt

The filename is very long, so for convenience I’ve used tab completion to produce the second filename. Now I want to replace the underscores with something else, for example \ .

I’m using vim in the CLI, so I press ESC to enter (vim) normal mode, go to the start of the second filename, and then press : to enter the command s/_/\ /. FYI, after entering the : here, I’m seeing this:

mv here_is_a_way_too_long_filename.txt here_is_a_way_too_long_filename.txt
execute: s/_/xxx/

but I cannot type a space or press return to execute this vim substitution command. In fact, I can only exit this extra execute: line by pressing ^C.

I’ve also tried numerous variations of the substitution command, to no avail:

s/_/xxx/
gs/_/xxx/
%s/_/\\ /  ← NB: I can’t actually enter the space here.
s/_/\\s/
s/_/[:space:]/
... and so on

I don’t want to resort to the command history. This post describes doing something similar but for a previous command in the command history.

What I want to end up with (in the above example) is this:

mv here_is_a_way_too_long_filename.txt here\ is\ a\ way\ too\ long\ filename.txt

after which I press enter to execute the mv command in the shell (eg. zsh).

I want to do this with vim in the CLI if possible. Notes on spaces in filenames are outside the scope; assume I’m aware of those perils.

Philippos
  • 13,237
  • 2
  • 37
  • 76
TransferOrbit
  • 183
  • 1
  • 7
  • 3
    FYI: You aren't actually using Vim there. You're using your shell's vi key bindings (or "vi mode"), which has some movement and basic editing shortcuts bound to Vim-like keys. That's about it for them. If you want to actually edit the current line in Vim, there are keybindings available for that in [bash](https://unix.stackexchange.com/a/85393/70524) and [zsh](https://unix.stackexchange.com/a/6622/70524). Here, when you press `:`, you're just entering Zsh's command mode, where you can enter [ZLE commands](https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html), *not* Vim commands. – muru Sep 05 '22 at 09:23

0 Answers0