在shell脚本中执行VIM命令

Nik*_*nov 15 vi macos vim bash shell

我正在编写一个运行命令行程序(Gromacs)的bash脚本,保存结果,修改输入文件,然后再次循环执行该过程.我正在尝试使用VIM来修改输入文本文件,但我无法找到执行内部VIM命令的方法,如:1234,w,x,dd等.在VIM中打开输入文件后从.sh文件中获取("vim conf.gro").

有没有实用的方法从shell脚本执行VIM命令?

Ken*_*ent 13

我认为vim -w/W and vim -s这就是你要找的.

您也可以录制的"vim操作/键序列" vim -w test.keys input.file,您也可以编写test.keys.例如,将其保存在文件中:

ggwxjddZZ
Run Code Online (Sandbox Code Playgroud)

这样做:

move to 1st line, 
move to next word,
delete one char,
move to next line, 
del the line. 
save and quit.
Run Code Online (Sandbox Code Playgroud)

使用此test.keys文件,您可以执行以下操作:

vim -s test.keys myInput.file
Run Code Online (Sandbox Code Playgroud)

您的"myInput.file"将由上述操作处理并保存.你可以在shell脚本中拥有该行.

vimgolf使用相同的方式来保存用户解决方案.


Pet*_*ker 10

你可以通过-c旗帜脚本Vim .

vim  -c "set ff=dos" -c wq mine.mak
Run Code Online (Sandbox Code Playgroud)

然而,这只能让你到目前为止.

  • 从你给出的命令看起来你正在尝试运行一些正常的命令.你需要使用:normal.例如:norm dd
  • 在命令行中写下所有这些都是在寻找麻烦.我建议你制作一个vim文件(例如commands.vim)然后:source通过-S.
  • 您可能希望获得良好且一致的vim的ex命令.看一眼:h ex-cmd-index

所以你最终会得到这样的东西.用你所有的vim命令commands.vim.

vim -S commands.vim mine.mak
Run Code Online (Sandbox Code Playgroud)

您可能还想查看使用sed和/或awk进行文本处理.


Ing*_*kat 6

备择方案

除非你真的需要特殊的Vim的功能,你可能最好使用非交互式工具一样sed,awk或Perl/Python的/ Ruby的/ 你最喜欢的脚本语言在这里.

也就是说,您可以非交互式使用Vim:

无声批处理模式

对于非常简单的文本处理(即使用Vim,如增强型'sed'或'awk',可能只是受益于:substitute命令中增强的正则表达式),请使用Ex模式.

REM Windows
call vim -N -u NONE -n -es -S "commands.ex" "filespec"
Run Code Online (Sandbox Code Playgroud)

注意:静默批处理模式(:help -s-ex)会混淆Windows控制台,因此您可能必须cls在Vim运行后进行清理.

# Unix
vim -T dumb --noplugin -n -es -S "commands.ex" "filespec"
Run Code Online (Sandbox Code Playgroud)

注意:如果"commands.ex"文件不存在,Vim将挂起等待输入; 更好地检查它的存在!或者,Vim可以从stdin读取命令.您还可以使用从stdin读取的文本填充新缓冲区,如果使用-参数,则从stderr读取命令.

完全自动化

对于涉及多个窗口的更高级处理,以及Vim的真实自动化(您可以与用户交互或让Vim运行以让用户接管),请使用:

vim -N -u NONE -n -c "set nomore" -S "commands.vim" "filespec"
Run Code Online (Sandbox Code Playgroud)

以下是使用的参数的摘要:

-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.
Run Code Online (Sandbox Code Playgroud)