Ever have a very long shell command that when you run you realize has a mistake right in the middle? Ctrl-A will take you to the beginning and Ctrl-E will take you to the end, but what if you’d really like to search and replace a word, or delete a chunk, VIM would be perfect for such a task. Well, this tip is for you.
Here is a somewhat long command you can test with:
for i in `cat file | grep -P ^value[0-9] | awk -F: '{print$2}'`; do ssh $i "ps aux | grep value"; done
Let’s say that I want to change the print$2 to print$3. Doing this using the cursor I would have to move sequentially across the command and stop in the right place, then delete or backspace and type the new charactor. With this tip, I can type Ctrl-X, Ctrl-E and bash will load my default editor (which is VIM, right? ^1) and in it you’ll see your long command. Use “f2″ to move to the 2 and then “r3″ to replace it, then write and quit using “ZZ” or “:wq” and VIM will exit and then bash will execute the newly edited command.
Thanks to Justin Burke for showing me this one!
^1. put this is your ~/.bashrc file “export EDITOR=vim”




Ah, another note… when you’re editing the command line in vim and you decide you don’t want to execute the command line you can exit with :cq instead of :wq (or ZZ). Doing so will be the same as pressing ^C in bash to cancel the command.
If you want the full vim experience you should be using ’set -o vi’ in bash. That changes the command line editing mode to use vi-like bindings (i to enter insert mode, ESC to get out). In normal mode, pushing ‘v’ will start up EDITOR.
Bartman, thanks for the comments. I am still learning to love vi mode in bash. It breaks using CTRL-A and CTRL-E to get to the start and end of the line and that really bugs me. That’s what I like about this tip, I can keep bash the way I like it, and still be only two key strokes away from editing the command. The extra key stroke is worth it to me.