我正在编写一个Bash脚本,它可以运行一个命令行程序(Gromacs),保存结果,修改输入文件,然后再次循环执行。
我尝试使用Vim来修改输入文本文件,但我没有找到一种在打开我的输入文件后从.sh文件中执行内部Vim命令(如:1234、w、x、dd等)的方法。
是否有一种实用的方式可以从shell脚本中执行Vim命令?
我认为 vim -w/W 和 vim -s
是你要找的。
你也可以使用 vim -w test.keys input.file
来记录"Vim操作/按键序列"。你也可以编写 test.keys
,例如将以下内容保存在文件中:
ggwxjddZZ
这样做就可以了:Move to the first line,
move to the next word,
delete one character,
move to the next line,
delete the line, and
save and quit.
有了这个test.keys
文件,你可以做到:
vim -s test.keys myInput.file
上述操作将处理您的“myInput.file”并进行保存。您可以在shell脚本中添加该行。
VimGolf使用相同的方式保存用户的解决方案。
你可以通过-c
标志来编写Vim脚本。
vim -c "set ff=dos" -c wq mine.mak
然而,这只能帮助你到这个程度。
:normal
。例如::norm dd
commands.vim
),然后通过-S
使用:source
。:h ex-cmd-index
因此,您最终将得到像这样的东西。将所有Vim命令放在commands.vim
文件中。
vim -S commands.vim mine.mak
您可能也想尝试使用sed
和/或awk
来进行文本处理。
除非你确实需要特殊的Vim功能,否则最好使用像sed
、awk
或Perl / Python / Ruby / 你喜欢的脚本语言在这里这样的非交互式工具。
话虽如此,你可以非交互地使用Vim:
对于非常简单的文本处理(即像增强版的'sed'或'awk'一样使用Vim,也许只是在一个:substitute
命令中受益于增强的正则表达式),使用Ex-mode。
REM Windows
call vim -N -u NONE -n -es -S "commands.ex" "filespec"
:help -s-ex
)会破坏Windows控制台,因此您可能需要在Vim运行后执行cls
来清理它。# Unix
vim -T dumb --noplugin -n -es -S "commands.ex" "filespec"
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.
vim -c "dd" myfile.txt
,我会得到 E492: Not an editor command: dd
。 - Sridhar Sarnobatdd
是正常模式命令,但自动化执行 Ex 命令。对于删除,您可以选择 :delete
,或使用 :normal! dd
;您还可以指定要删除的目标行号/范围。 (哦,只需删除整行,您不需要 Vim - sed
就可以胜任。) - Ingo Karkatvim
的更多功能,超越传统用法,将其用作过滤器是利用Unix哲学更多力量的一种方式。 - Sridhar Sarnobat
vim
而不是其他编辑器,比如sed
吗?你能否在vim
的ex
模式下使用它,该模式不使用全屏幕(因此更适合用于脚本)?你在编写脚本时到底想做什么编辑操作? - Jonathan Leffler