Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a list of vim commands on a text file?

Tags:

vim

I have a text that's around 1000 lines long, and I have a bunch of vim commands I want to apply to it. Lots of regex find-and-replace stuff. For example:

  • :%s/^[^\$\$]/def
  • :%s/\$\$/
  • %s/='/ = ['

I could copy and paste those commands one by one, but that's work I'll have to do again every time I receive a new version of this file. I'm wondering if there's a way to save a long list of commands that I can then apply to the file? Thanks!

like image 930
nathan.hunt Avatar asked Jan 18 '17 15:01

nathan.hunt


1 Answers

registers

You can put them all into a register, either by typing those commands in a scratch buffer and then yanking into a register, or via explicit assignment:

:let @a = "%s///\n%s///"

Then, execute via :@a

Depending on your Vim configuration, the register contents may persist across sessions (cp. :help viminfo), but you must be careful to not override them.

scripts

A longer-lasting and more scalable solution is putting the commands into a separate script file, ideally with a .vim extension. You can put them anywhere (except ~/.vim/plugin, unless you want them executed automatically), and then run them via

:source /path/to/script.vim

custom commands

If you need a set of commands very often, you can give them a name and turn them into a custom command:

:command! MyCommands %s/// | %s///

Put this into your ~/.vimrc, or (if it's filetype-specific), make it a :help ftplugin.

like image 120
Ingo Karkat Avatar answered Sep 17 '22 04:09

Ingo Karkat