Vim tips——Working with external commands
A common sequence of events when editing files is to make a change and then need to test by executing the file you edited in a shell. If you're using vim, you could suspend your session (ctrl-Z), and then run the command in your shell.
That's a lot of keystrokes, though.
So, instead, you could use vim's built-in "run a shell command"!
:!{cmd}Run a shell command, shows you the output and prompts you before returning to your current buffer.
Even sweeter, is to use the vim special character for current filename: %
Here's ':! %' is in action!


A few more helpful shortcuts related to executing things in the shell:
:!By itself, runs the last external command (from your shell history):!!Repeats the last command:silent !{cmd}Eliminates the need to hit enter after the command is done:r !{cmd}Puts the output of $cmd into the current buffer
-----------------------------------------------------------------------------------------------------------------------------------------------------
Vim is a powerful editing tool, but there are some things it just can't do. However, Vim lets you access shell commands and utilities without leaving Vim, and that lets you perform some amazing tricks.
If you run :shell or just :sh while you're in the editor, Vim (or Gvim, if you're partial to Vim's GUI) will place you in an interactive shell. You can run whatever commands you want, and resume your Vim session by exiting the shell.
As most other *nix applications, you can also pause Vim with Ctrl-z, which will drop you back to the shell. When you're finished, you can resume Vim with fg. (This is a feature of the shell, not a Vim feature.)
Have you ever started editing a file, made a bunch of changes, and then typed :w to write your changes, only to find that the file is read-only? You can deal with that in a couple of ways, but one of the easiest things to do is to invoke a shell from within Vim and change the file's permissions before you save it again.
Bang!
Vim also allows you to execute a command directly from the editor, without needing to drop to a shell, by using bang (!) followed by the command to be run. For instance, if you're editing a file in Vim and want to find out how many words are in the file, run
:! wc %
This tells Vim to run the file (%) through the wc utility and report the results. Vim will display the command output at the bottom of the editing window until you press Enter. Note that this command runs the file through the command, and not the contents of the buffer -- so if you haven't saved recently, it won't report your most recent word count.
Bang works best with non-interactive commands. You wouldn't want to run top or another interactive command using :! command, but you could drop to a shell and run such a command with :sh or Ctrl-z.
The bang command can be useful if you're using Vim for programming. If you're writing a PHP script, for example, you could use PHP's syntax check option (-l) to see if your script has any syntax errors:
:! php5 -l %
If you're working on a script or project, you might want to check it regularly, and with minimal typing. You can scroll through Vim's command history by using the up arrow, but if you just want to rerun the last external command, you can use :!! instead.
Reading command output
Most Vim users are already familiar with using the read command, which inserts text from a specified file into the current buffer, like so:
:r textfile
This is handy, but many users aren't aware that you can also read in the output of shell applications. For example, if you wanted to include a list of files from a specific directory, you could include them using this read command:
:r ! ls -1 /home/user/directory
This tells Vim to execute the command ls -1 /home/user/directory and then redirect the output of that command into the buffer. You could also use this feature to read the text from a Web page into the file that you're editing, using a text-mode browser such as w3m. It's pretty simple to grab a page using w3m and dump it right into your editing session without leaving Vim:
:r ! w3m http://en.wikipedia.org/wiki/Vi -dump
The -dump option tells w3m to simply spit out the Web page as plain text and exit.
It's also possible to execute multiple commands to process your text before reading it into Vim. A simple example would be to list the directory contents, then pipe the output to the sort command to sort the filenames in reverse order, before inserting the text into the current buffer:
:r ! ls -1 /home/user/directory | sort -r
The read command can also come in handy if you're prepping an incident report from server logs. Let's say you wanted to include all of the errors in an Apache log that include a specific string. You could grep the log and insert the input into your Vim session:
:r ! grep string /var/log/apache2/site-error.log
Vim makes it easy to redirect the output of most standard *nix utilities into a file, and to pipe text from the file it's editing into standard *nix utilities.
Filtering text through external filters
While in Vim, you can select a range of text and run that text through an external command. In visual mode, just highlight the text you want to work with, then run :! commandname. The highlighted text will be replaced by the output of the command. Let's say you wanted to use weak encryption on part of a file by running it through the rot13 utility. Use v, V, or Ctrl-v to enter the visual mode of your choice and select the text you want to encrypt. Then run :! rot13to replace the selected text with rot13-encoded text. This might be handy when composing an email containing a spoiler about the latest episode of Battlestar Galactica for sending to a mailing list. It's trivial for recipients to decode rot13-encoded text, but the folks who don't like spoilers won't have any surprises ruined by skimming over the text.
You can also specify a range of lines to process, rather than selecting lines in visual mode. For instance, to filter lines 20 through 25 of a file through rot13:
:20,25 ! rot13
Vim will run the text through rot13 and insert it in place of the existing text. If you accidentally overwrite some text in Vim that you didn't mean to, don't worry -- Vim's undo command (u) allows you to restore the original text.
Using a different shell
By default, Vim should use your default shell. If you want to make sure that Vim's using your default shell, you can check the value of the shell option by running this query:
:set shell ?
Vim will display shell=/bin/bash, or whatever the shell is set to. Note that this works with other options as well, so you can use :set option ? to check the value of any option within Vim.
If you'd like to change the value of the shell temporarily, run :set shell=/path/to/shell with the correct path to your chosen shell. For instance, on Ubuntu, if you want to use the Korn shell, you can run :set shell=/usr/bin/ksh -- assuming you have the Korn shell installed.
To make the change of shells permanent, open your ~/.vimrc and add this line:
set shell=/path/to/shell
The next time you start a Vim session, the new shell option will be set.
Get in the habit of using Vim's :shell command and the :! utility, and you'll find that you can be even more productive while using Vim than you might have thought possible.
Vim tips——Working with external commands的更多相关文章
- Vim tips
1.光标移动: (1).NG -> 移动到第N行,或者使用:N (2).gg -> 移动到第一行 (3).G -> 移动到最后一行 (4).单词移动: w -> 移动到下一个单 ...
- vim tips 集锦
删除文件中的空行 :g/^$/d g 表示 global,全文件 ^ 是行开始,$ 是行结束 d 表示删除该 这里只能匹配到没有白空符的空行,假如要删除有空白符的空行,则使用: :g/^\s*$/d ...
- 最佳vim技巧
最佳vim技巧----------------------------------------# 信息来源----------------------------------------www.vim ...
- VIM命令集
Command Action Notes vim file +54 open file and go to line 54 any : command can be run using + on co ...
- (转) 共享个很棒的vim配置
发现了一个很棒的vim配置方法,现在共享给大家. https://github.com/kepbod/ivim ivim - The Vim Distribution of Xiao-Ou Zha ...
- Vim ide for shell development
Source : This article is part of the ongoing Vi / Vim Tips and Tricks Series. As a Linux sysadmin or ...
- vim 常用快捷键 二[转]
键盘移动 (Move) 一切都从键盘的移动k -> 上 upj -> 下 downh -> 左 leftl -> 右 rightz -> 重画屏幕,当前光标变成屏幕的第一 ...
- vim 常用 NERDTree 快捷键
ctrl + w + h 光标 focus 左侧树形目录 ctrl + w + l 光标 focus 右侧文件显示窗口 ctrl + w + w 光标自动在左右侧窗口切换 ctrl + w + r 移 ...
- 请通过vim练习:vim vimtutor
vim vimtutor ================================================================================ W e l ...
随机推荐
- Python之pandas数据加载、存储
Python之pandas数据加载.存储 0. 输入与输出大致可分为三类: 0.1 读取文本文件和其他更好效的磁盘存储格式 2.2 使用数据库中的数据 0.3 利用Web API操作网络资源 1. 读 ...
- SQL SERVER 执行计划各字段注释
SET SHOWPLAN_ALL使 Microsoft® SQL Server™ 不执行 Transact-SQL 语句.相反,SQL Server 返回有关语句执行方式和语句预计所需资源的详细信息. ...
- Java 基础入门随笔(11) JavaSE版——继承、覆盖、抽象类
1.面向对象的特征二:继承 定义: 指一个对象直接使用另一对象的属性和方法. 继承好处: 1.提供代码的复用性. 2.让类与类直接产生了关系,给第三个特征多态提供了前提. java中支持单继承.不直接 ...
- 4星|《DK商业百科》:主要商业思想与事件的概括
全书分为以下6章:1:企业的起步与发展:2:领导和人力资源:3:理财:4:战略和运营:5:营销管理:6:生产与生产后.每章有拆分为成多个比较小的专题,阐述相关专题的主要的商业思想与实践. 基本是作者按 ...
- 329.-io流(字符-练习-复制文本文件二)
//每次读取的字节长度,一般都是1024的倍数 private static final int BUF_SIZE = 1024; public static void main(String[] a ...
- TypeError: 'TestCase' object is not iterable
这个异常呢其实是因为我对list没有足够熟悉 我一开始很疑惑,明明已经正确返回testcase对象了呀,为啥会报TypeError: 'TestCase' object is not iterable ...
- ThinkPHP---AR模式
[前言] 在之前学习框架时介绍过 (1)什么是框架? ①框架是一堆包含了常量.方法和类等代码集合: ②半成品应用,只包含了项目开发时的底层架构,并不包含业务逻辑: ③包含一些设计模式,例如单例模式,工 ...
- 配置redis三主三从
主从环境 centos7.6 redis4.0.1 主 从 192.168.181.139:6379 192.168.181.136:6379 192.168.181.136:6380 192.168 ...
- NOIP 前的垂死挣扎
计划每天十题吧,可能会一天水题一天难题吧.题目以杂题为主,没有专题可言. 10.11 计划: [x] P2939 [USACO09FEB] 改造路 Revamping Trails [ ] P3601 ...
- Linux学习笔记(四) vi编辑器
一.vi 编辑器 vi 编辑器 (Visual Interface) 是所有 Unix 及 Linux 系统下标准的编辑器,相当于 Windows 系统中的记事本 它有三种模式,分别是: Comman ...