When you need to edit a file hosted on a remote host, it will be nice if you can edit the remote file locally, as if it were a local file. Of course you could set up NFS over ssh tunnel to achieve that, but that would be an overkill if this is just one-time usage. So the question is: is there a way to edit a remotely located file over ssh?
That is when vim (short for "Vi IMproved") can help. vim can be considered "vi on steroid," with extensible features that greatly improve the vi's default editing environment. The extensibility of vim is achieved by using "plugins". One such vim plugin is netrw which enables reading and writing files over networks. netrw supports various application layer protocols including ftp, http, scp, rsync and rcp.
If you would like to edit a remote file over ssh using vim, you can do the following.
$ vim scp://user@remote_host//home/user/path/file
Note the double "/"s for the root directory of the remote host. The above vim command opens a file located on a remote host for editing. Behind the scene, vim uses scp to fetch the requested file from a remote host, stores the file in /tmp, and finally opens it for editing.
When you attempt to save your changes to the file, the changes are first applied to a local copy in /tmp, which is then uploaded via scp to the remote host.
Since the behind-the-scene network transfer is handled by netrw plugin, you can edit any remote file using traditional vi interface transparently.
Subscribe to Xmodulo
You can have daily Linux tutorials and FAQs delivered to your email inbox. Simply enter your email address below to subscribe to our mailing list. You will receive hands-on guides and carefully written tutorials related to Linux, everything for free.