您好,我有一个问题:
我正在编写一个shell脚本,需要向vim传递输入。
具体解释如下:
我已经编写了一个不可更改的shell脚本,以下是代码:
sudo vim /mnt/etc/{hosts,hostname,ports}
由于这个主机文件已经打开,我们可以通过:n手动转到主机名文件,端口文件也是如此。
但我必须从我的.sh文件执行同样的操作。 我还必须编辑端口文件,并在完成后通过:wq命令保存并退出。
我该怎么做?
除非你真正需要特殊的Vim功能,否则最好使用非交互式工具,如sed
、awk
或Perl / Python / Ruby / 你最喜欢的脚本语言。
即便如此,你也可以以非交互方式使用Vim:
对于非常简单的文本处理(即像增强版的'sed'或'awk'一样使用Vim,也许只是在:substitute
命令中从增强的正则表达式中受益),请使用Ex模式。
# Unix
vim -T dumb --noplugin -n -es -S "commands.ex" "filespec"
"commands.ex"
文件不存在,Vim将挂起等待输入;最好事先检查其是否存在!或者,Vim可以从标准输入读取命令。如果您使用-
参数,则还可以从标准错误读取缓冲区中从标准输入读取的文本,并读取命令。
对于涉及多个窗口的高级处理和真正的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.
sed
并进行了一些更改,最终它起作用了。 - r15
.sh文件
中并运行它呢? - Donovansed
是更合适的方法。 - Donovansed
或awk
,而不是vi
。 - Donovan