我有多个文件要编辑。我必须进行某些更改,比如根据模式复制一些行,然后我必须在不同的地方插入一些文本。我打算使用 vim 来自动化我的任务。我写了这个脚本
gg
i
some text to add
some more text to add
<esc>
:%s/text/TEXT/g
:wq
但它只是打开 vim 编辑器,甚至在文件中插入命令,然后我必须手动删除以下文本
<esc>
:%s/text/TEXT/g
:wq
并保存文件。
我正在调用以下命令:
vi -s vimscript mytextfile
我之前使用 vim 脚本来做除了插入文本之外的其他事情,例如搜索和替换或复制粘贴模式等。
最佳答案
备选方案
除非您真的需要特殊的 Vim 功能,否则最好使用非交互式工具,例如 sed
、awk
或 Perl/Python/Ruby/这里是你最喜欢的脚本语言。
也就是说,您可以非交互地使用 Vim:
静默批处理模式
对于非常简单的文本处理(即像使用增强的 'sed' 或 'awk' 一样使用 Vim,也许只是受益于 :substitute
命令中增强的正则表达式),使用 Ex -模式。
REM Windows
call vim -N -u NONE -n -es -S "commands.ex" "filespec"
注意:静默批处理模式 (:help -s-ex
) 会扰乱 Windows 控制台,因此您可能必须执行 cls
才能在 Vim 之后进行清理跑。
# Unix
vim -T dumb --noplugin -n -es -S "commands.ex" "filespec"
注意:如果 "commands.ex"
文件不存在,Vim 会挂起等待输入;最好事先检查它的存在!或者,Vim 可以从标准输入读取命令。如果使用 -
参数,您还可以使用从 stdin 读取的文本填充新缓冲区,并从 stderr 读取命令。
全自动化
对于涉及多个窗口的更高级处理,以及真正的 Vim 自动化(您可能与用户交互或让 Vim 运行以让用户接管),请使用:
vim -N -u NONE -n -c "set nomore" -S "commands.vim" "filespec"
以下是所用参数的摘要:
-T dumb Avoids errors in case the terminal detection goes wrong.
-N -u NONE Do not load vimrc and plugins, alternatively:
--noplugin Do not load plugins.
-n No swapfile.
-es Ex mode + silent batch mode -s-ex
Attention: Must be given in that order!
-S ... Source script.
-c 'set nomore' Suppress the more-prompt when the screen is filled
with messages or output to avoid blocking.
关于bash - vim 如何插入文本、保存和退出 bash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22575125/