Editing Files on the Command Line
local graph
Chapter 4 — Editing Files on the Command Line
Section titled “Chapter 4 — Editing Files on the Command Line”Editing text on the command line is often a hard requirement due to the constraints of production systems, which tend to lack a graphical user interface. However, becoming fluent at editing text on the command line has many benefits even outside of those systems – indeed, even when you have graphical text editors or integrated development environments (IDEs) available.
For example, many full-featured text editors and IDEs support the patterns you’ll learn about in this chapter, which means the speed and efficiency you gain is transferrable to other tools. In fact, you can use the shortcuts you’ll learn in this chapter for all kinds of things, from quickly finding and replacing text to correcting a misspelled word in the middle of a long shell command.
You might even find similar shortcuts built into your favorite tools (sometimes via plugins); for example, you’re only a few Google searches away from discovering email clients, browser plugins, and web applications that support the vim keyboard shortcuts that you’ll learn later in this chapter.
Learning how to think in the efficient patterns that these minimal, text-only interfaces require can help you find more efficient ways of doing things you’ll have to do every day, preventing you from wasting time tediously clicking through graphical menus or wizards when you can accomplish the same task with just a few keystrokes.
Note
Many extremely minimal (or highly secure) environments also tend to strip text editors out of production images, although that doesn’t improve security (cat, echo, mv, and input/output redirection are more than enough to improvise a workable text editor in a pinch). You — like hackers everywhere — will likely end up installing nano or vim in quite a few Docker containers over the course of your life.
In this chapter, you’ll learn the basics of two text editors: one that we think is the easiest to get started with (nano) and another that we think is the best long-term learning investment for your career (vim). You’ll get the basic context for how command-line text editing is done on Linux, dive into nano and vim, and finally, learn how to avoid the most common editing mistakes. We’ll also show you how to tweak your shell to automatically use your preferred editor when possible.
Nano is a small and easy-to-use CLI text editor. One of the features of nano — you might even call it the main feature — is that it prominently has a keyboard-shortcut cheat sheet bolted to the bottom of your screen while you happily edit text in your terminal. This is particularly useful if you’re under stress and not used to editing text on the command line.
Nano is good in a pinch, but you won’t find it installed in more minimal environments (such as Docker containers or production VMs). Be aware that nano also tends to automatically make backup files (~yourfile.txt), thereby potentially polluting the filesystem.
Installing nano
Section titled “Installing nano”On all the popular Linux distributions you’re likely to use, the package name for nano is nano – use your preferred OS’s package manager to install it (in this case, we’re installing it on Ubuntu):
apt-get install nanoNano cheat sheet
Section titled “Nano cheat sheet”You can find an official, up-to-date nano cheat sheet here: https://www.nano-editor.org/dist/latest/cheatsheet.html
Some of the most useful commands are called out in the following sections.
File handling
Section titled “File handling”- Ctrl + S: Save current file
- Ctrl + O: Offer to write file (“Save as”)
- Ctrl + R: Insert a file into the current one
- Ctrl + X: Close buffer, exit from nano
Editing
Section titled “Editing”- Ctrl + K: Cut the current line into a cutbuffer
- Ctrl + U: Paste contents of the cutbuffer
- Alt + 3: Comment/uncomment a line/region
- Alt + U: Undo last action
- Alt + E: Redo last undone action
Search and replace
Section titled “Search and replace”- Ctrl + Q: Start backward search
- Ctrl + W: Start forward search
- Alt + Q: Find next occurrence backward
- Alt + W: Find next occurrence forward
- Alt + R: Start a replacing session
Vi (often referred to as ex-vi or nvi) is a command-line text editor. Vim (vi iMproved) is an extended version, that many people use as an entire IDE. vi and vim share the same basic commands and keyboard bindings, so if you just learn the basics, you’ll be fine no matter what kind of ancient or modern system you log in to.
Fair warning: vim is complicated and has a relatively steep learning curve. It’ll probably take a few weeks of spare time studying and experimenting to get comfortable with it – comparable to setting up your first Linux web server or writing your first 500-line program.
The wonderful thing about learning vim is that you can use it locally on your laptop or remotely on a server that has no GUI, and the editing experience is the same – beautifully efficient – in both places. To use it effectively, both a shift in mindset and an understanding of its vocabulary (the commands and modes we’ll get into) are important.
As with learning any other skill, some dedicated practice followed by consistent use of the editor is essential to really build up an understanding and feel comfortable. Some initial struggle and confusion will likely be part of that. Please don’t let this deter you!
Vim is a modal editor, meaning that the same keys do different things depending on which “mode” you’re in. For example, when you’re in insert mode, your keypresses will simply be written into the file (or buffer) you’re editing – much like your IDE or Microsoft Word. However, in normal mode, pressing those same letter keys will execute whatever keybinding they are tied to. Once you’ve adjusted to that idea – modal editing – the rest of vi/vim is just practice.
For example, if you start vim and type a lowercase i twice, the first i will enter insert mode, while the second will actually write an i character in the editing window (buffer) that you’re editing a file with. If this sounds confusing right now, it’s okay. Even if you never choose to use vim as your regular IDE, you’ll feel a lot more comfortable with its basics by the end of this chapter.
Note
It is also worth mentioning that another vim-like editor, nvim (neovim), has started gaining traction at the time of writing this book. Most of what applies to vim also applies to nvim, so there is no need to worry about which one to get started with. The major differences are around plugin development, so you won’t lose anything if you decide to switch from vim to neovim down the road, as we have.
Vi/vim commands
Section titled “Vi/vim commands”Here are some basic vi(m) commands – hit Escape before using any of these, to make sure you’re in Normal mode.
- v – enter visual mode. This feature only exists in vim (not vi) and can easily be overused in the beginning because it’s familiar to people coming from other editors.
- ESC — exit whichever mode you’re in and go to Normal mode, where you can give commands.
Command mode
Section titled “Command mode”Command mode can be reached from normal mode (hit Escape) by typing a colon (:). We’ve included the colon in the commands below for clarity.
Helpers
Section titled “Helpers”:set number– show line numbers.:set paste– this is helpful if you want to paste things into vim and don’t want it to interact with indentation. You can disable it again with:set nopaste.
Exiting
Section titled “Exiting”:q– quit:q!– quit without saving (force quit):w– write (“save”) the file:wq– write and quit:wqa– only vim; helps when multiple panes are open, such as a plugin opening a file browser on the side
Normal mode
Section titled “Normal mode”Normal mode is the mode you’re in when you start vim, before typing anything. You can always get back to normal mode by hitting the Escape key.
Navigation
Section titled “Navigation”- k – move up
- j – move down
- l – move right
- h – move left
Alternatively, it is possible to use the arrow keys, but it can be helpful to think in terms of vi shortcuts, instead of trying to drive vi(m) like an ordinary editor. We’ve found that it helps to stick to vi’s movement keys when you’re practicing with it.
- w – next word
- b – beginning of the current word or previous word
- ^ or 0 – go to the beginning of the line
- $ – go to the end of the line
- gg – go to the beginning of the file
- G – go to the end of the file
Editing
Section titled “Editing”- i – enter insert mode (write actual text). I inserts at the beginning of the line.
- a – insert text, appending after the cursor. A appends on the end of the current line.
- o – open a new line (O opens a new line before the current one).
- / – search for pattern (regexes work here; use ENTER to search and n and SHIFT + n to cycle forward or backward through search results).
- dd – delete (and cut) the current line.
- y – yank (copy) selected text.
- yy – yank (copy) the current line.
- p – put/paste text after the cursor.
- u – undo the last change.
- CTRL + R – redo.
- nX – where n is a number and X is a command, will execute X n times. For example, 3dd will delete three lines.
Tips for learning vi(m)
Section titled “Tips for learning vi(m)”Over a few weeks of normal editing tasks, you can become quite comfortable with vim. That said, it’s not always easy to get started. Here are our tips for making the journey smoother.
Use vimtutor
Section titled “Use vimtutor”Vim comes with a built-in tutorial. If you want to get started with vim, this is probably the very first thing you want to do. Just run vimtutor on your command line to open vim and the tutorial.
Think in terms of mnemonics
Section titled “Think in terms of mnemonics”When using vi(m) to edit files, it’s common to “build sentences” using the commands you saw above. For example, d2w means “delete two words.” While we tried to mention fitting words in the command list above, different people prefer different mental concepts, so don’t feel scared to build up your own vocabulary.
Avoid using arrow keys
Section titled “Avoid using arrow keys”Avoid using arrow keys and consider disabling this feature. It prevents you from thinking of vim as another editor and reduces the time it takes until you’re comfortable with its standard keybindings. Don’t worry; although this may feel strange at the beginning, you will get used to the basic vim keybindings after a few sessions.
Avoid using the mouse
Section titled “Avoid using the mouse”While vim can be used with a mouse for visual selection, it makes sense to resist this temptation and keep training your working memory of the keyboard shortcuts. Otherwise, you’ll switch back and forth and not be comfortable when it counts, like when you’re troubleshooting on a remote server that has no mouse input at three in the morning.
Don’t use gvim
Section titled “Don’t use gvim”While gvim (graphical/GUI vim) can be useful, it is not a good idea to use its graphical shortcuts when no proper terminal is available. The benefit of vi(m) is that it allows for effective text manipulation via the keyboard when you don’t have a graphical environment available – like the many Linux servers you’ll be troubleshooting after reading this book!
Avoid starting with extensive configuration or plugins
Section titled “Avoid starting with extensive configuration or plugins”A typical beginner’s mistake is starting with someone else’s vim configuration. Although they seem useful at first, heavily customized vim setups can hinder you when you’re just trying to learn the basic concepts. Extensive configurations will not magically make you more productive, especially not in the beginning. Once you become more confident, you will find yourself writing your own configuration.
Another thing to avoid is excessive plugin usage, especially early on. Occasionally, plugins break things, which can become a burden and lead to more issues. Vim plugin troubleshooting is not something you want to deal with when you are just getting started. Third-party configuration files and plugins can be amazingly useful, but they can also become a crutch: when you are suddenly thrown into an environment outside of your development machine, you won’t be able to rely on all of that fancy stuff. If you’ve come to depend heavily on a custom workflow, even basic edits can become difficult and frustrating, especially under stress.
A more sensible approach is to start out with a minimal configuration and only add bits that you fully understand (and that you’re sure you will need). Your time is much better spent actually using the editor on real projects, because it trains you to retain the most important vim shortcuts in your working memory. It takes some time, but eventually you will use them without really thinking about the actual commands, rather just thinking in terms of the mnemonics you’ve made up for yourself.
Here is an example of a minimal vim configuration that might be helpful in the beginning. Feel free to change it, or just pick out parts that seem useful.
Put this into your $HOME/.vimrc:
"This breaks compatibility with vi, saying that we want to use the benefits of vimset nocompatible" Enable syntax highlightingsyntax on" Increase the command history to be very bigset history=10000" Indent based on the previous lineset autoindent" Make it so searches wrap around at the end of the fileset wrapscan" Show the current mode in the command lineset showmode" Displays partial commands in the last lineset showcmd" Highlight searchesset hlsearch" Use case insensitive searchset ignorecase" Don't use case insensitive search use when using capital lettersset smartcase" Display the cursor position at the bottomset rulerVim bindings in other software
Section titled “Vim bindings in other software”Should you start enjoying and preferring the way vim works, it is worth mentioning that many text editors and IDEs have options and plugins to switch to a vim input mode. There are even web browsers with vim-style inputs!
If you’re curious or would like a review of the vim material in this chapter, you can find a video tutorial that covers some of the most important parts of this chapter (and even some extra vim features!) here: https://www.youtube.com/watch?v=ggSyF1SVFr4
Editing a file you don’t have permissions for
Section titled “Editing a file you don’t have permissions for”Regardless of which editor you use, sometimes you’ll want to edit a file that your user doesn’t have write permissions for. For example, if you’re a regular user and you want to edit /etc/hosts – a file owned by root, and writable only by root – you’ll need to either become root or use the sudo command. See Chapter 7, Users and Groups, for more details.
While a command like sudo $EDITOR /etc/hosts can be used to edit files as root, a better approach is to use sudoedit to execute your editing command as root:
sudoedit /etc/hostsEDITOR=nano sudoedit /etc/hostsEDITOR=vi sudoedit /etc/hosts
The first example will use whatever editor you’ve got set in your EDITOR environment variable, while the other two commands pass in (or override) the EDITOR environment variable as part of the command.
Setting your preferred editor
Section titled “Setting your preferred editor”Linux and in fact all Unix-like systems allow you to set your preferred editor via the EDITOR environment variable. Most command-line software that launches an editor for certain tasks, like git when you make a commit or visudo editing your sudoers file, will use this variable to know which editor to open. You can set this EDITOR variable to a path to any editor you like, even graphical ones (provided your system has a graphical user interface installed):
bash-3.2$ echo $EDITORnanobash-3.2$ export EDITOR=vimNote that the interactive shell command above will only work until the current shell session is closed; to persist this setting in the Bash shell, I’d add it to my ~/.bashrc file. See Chapter 4, Using Shell History for more details.
Conclusion
Section titled “Conclusion”In this chapter, you learned how to edit text files on the command line. First, we introduced the easiest way to get started (nano), and then we showed you how to start graduating to a skillset that will pay dividends for the duration of your career: vi/vim and their keybindings, which you’ll find supported in an incredibly wide variety of software.
Use the cheat sheets in this chapter to get started with command-line editing, but know that after a day or two of practice, you’ll be ready to learn additional shortcuts and commands in vim. That’s best done through a combination of vimtutor, online cheat sheets, and YouTube videos. We also really like the book Practical Vim, 2 nd Edition, by Drew Neil.
Becoming comfortable with command-line text editing is one of the surest ways to look and feel like a professional when you’re working. Don’t neglect this skillset!