简体   繁体   中英

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

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!

registers

You can put them all into a register , either by typing those commands in a scratch buffer and then y anking 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 .

通常,您可以使用shell从shell运行vim命令

vim -c YourCommandHere

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM