CHAPTER 6

image

Editing Files on the Command Line

Believe it or not, one of the things you’ll end up spending most of your time doing on Linux is editing text files. They get absolutely everywhere and you’ll find them used for content, source code for applications, configuration files and start up scripts. The reason for this is that despite their somewhat basic and boring nature they are very useful for storing human readable information. When you combine this with ease of use, you know you’re on to a winner. Linux doesn’t have a registry like Windows and it’s extremely rare for applications not to use text files for their configuration. Even Sendmail which has an historically evil config file (so evil in fact you need to write a config file for yet another application which will then create the Sendmail config file for you) stores its config file as plain old text.

In this chapter we’re going to give you a brief overview of text files and how they’re used today. We’ll then introduce the two editors that we’re going to cover in this chapter (nano and vim) and then we’ll get into the real meat of the chapter and show you how to actually get things done.

What is a Text File?

When a computer stores data on disk, it can store data in one of two formats. It can either store data as a text file or it can store it as a binary file. Naturally as computers store everything as binary data (those good old 1’s and 0’s), what exactly makes a text file different from a binary file? After all, surely the text file must also be stored in a binary format. If you were thinking along those lines then you’re quite correct. It’s not so much how the data itself is stored, but more to do with how that data can be read.

The best way to appreciate the difference is to think about the page you’re reading right now. The reason you can understand what I’m writing is because we have implicitly agreed to use English to communicate. The content of this page has structure that we both understand. We start sentences with capital letters, we use punctuation to show when sentences end or when to stop for a breath. In short we have quite a complicated protocol here but it works because we are both capable of reading and writing English. We can understand both the structure (how the data is to be read and written) as well as the semantics (what the words actually mean). So, how about this sentence:

Goedemorgen. Hoe gaat het?

Straight away we can tell that it’s not English, after all, if it was we would be able to understand it. Unless you happen to speak Dutch (we don’t but our good friend does), you probably wouldn’t know which language it was written in. Even though the content doesn’t make sense, the structure itself does. We can see we have two sentences with one being a statement and the other being a question. In this particular case, we can stab a guess at what the first word means. If we pronounce it as we would English, it sounds very similar to good morning (which is actually what the word translates to). From that we can probably guess that the question is “how are you?”.

The reason we can do that is because although we don’t understand the content, Dutch and English share a common structure or format. We share an alphabet (although Dutch does have some characters not present in English) and punctuation (full stops, commas and question marks). Now you might not get the pronunciation right (it is after all a foreign language) but because we share a common structure, we can at least handle the content, even if we can’t understand it.

Figure 6-1 takes this one step further.

9781484211632_Fig06-01.jpg

Figure 6-1. Some Chinese Text

At least for the average reader of this book, Figure 6-1 will be uninteligable. It’s actually the same two sentences that appeared in our Dutch example but this time written in Chinese using Simplified Characters. To the uninitiated, there is no way to tell from this collection of characters how they should be pronounced. In fact depending on the dialect spoken, these characters could be pronounced in many different ways. This is because each character represents an idea rather than a sound, and once you recognize the idea, you know which word to say. This is why in China, it is possible for two people who cannot speak the same language to communicate perfectly well by reading and writing characters.

So why did we side track into foreign languages? Well, text files are like reading and writing English or Dutch. Whether the content makes sense or not depends on whether the reader can speak English or Dutch. This is similar to two applications and their config files. If you give an Apache web server configuration file to the Sendmail email server, it will spit it back in your face (Sendmail doesn’t speak Apache) but it can open and read in the file.

Chinese on the other hand is our example of a binary format. It is very alien for most western speakers (although arguably it is far more efficient, elegant and sophisticated than phonetic writing used in West European languages). Unless you know Chinese, you can’t understand the content or the implied structure. In computing terms, what you have is a blob of raw data that only makes sense to the application that wrote it.

Now you might be thinking that storing data in an arbritrary format is no big deal. After all, the application that wrote it is the application that will read it and as long as it understands the file, surely that’s enough. Well yes and no. What happens if the program breaks? What if you need to read the file on another machine? Perhaps the vendor has provided some special tools to do just that, but therein lies the problem - you need special tools.

Not so for text files. Text files can be opened in any text editor and no special tools are required. As the vast majority of Linux applications all use text files (we can’t think of any off the top of our heads that don’t), all you need to read or make changes to a configuration file is your favourite text editor and Linux has a stunning variety of editors to choose from. Thus you can become familiar with a single tool and then use that tool to reconfigure all of your applications, write source code when you’re doing scripting and even use it for writing books (which is precisely what we’re doing right now).

The Contenders

So the text editor is your Linux Swiss army knife and something you never want to leave home without. Of course, just like Swiss army knives there are many different text editors to choose from and also like swiss army knives, some have more features than others. Sometimes you want a basic text editor that just lets your open files, edit some text and then save the results. Other times you might want to do a complex search and replace or delete to the end of the line. Of course you can quite easily use one of the more featureful editors for all of your tasks, after all you don’t have to use the features if you don’t need them. That said it’s been our experience that people are generally familar with at least two text editors, one basic and one fully featured. In this book, that means nano and vim respectively.

The first text editor that we’re going to cover is nano. It’s a lightweight and easy to use text editor and it tends to be installed on most systems. Some later versions of nano have more features (such as syntax highlighting when writing source code) but all effectively look and work the same way. If you can use nano on your Pi, you’ll be able to use it equally well on any platform.

Nano was actually written to be a drop in replacement for the Pico text editor that used to ship with Pine, a text based email client. Pico can still be found on older systems (usually much older) and chances are if you can’t find nano you might still be able to find pico. As it’s a drop in replacement, the same commands and basic features that you are used to using in nano will also be available in pico. Combined this gives you coverage of most other Unix platforms as well as Linux.

Nano’s key selling point is its ease of use, but it does have a number of useful features. However these features are accessed from menus and while it has more than enough features for simply editing a config file, sometimes you need something with a little more power. This is where the vim editor comes in. It can do all the things that nano can do but it can do so much more that’s pretty much where the comparison ends. Vim also has syntax highlighting, different color schemes, the ability to cut and paste, delete blocks of text, indent chunks of text, open multiple files an show both at the same time and much more.

Now you might be thinking that if Vim is this great, you might save yourself a lot of headache by simply just learning how to use that text editor instead. Like nano it is available almost everywhere in some form or another and they all have the same basic features and accept the same commands. The reason we’re covering nano is that you can be up and running quite literally in just a few seconds. Its features are easy to explain and getting it to do what you want is really easy. Although vim users may disagree, in our experience, vim doesn’t exactly hold any ease of use awards. That said, if you really don’t want to learn two editors and feel that you’d rather just learn vim, that’s fine, you won’t really be missing out on anything, it just might take you a bit longer to get productive.

THE HOLY WAR - VI VS EMACS

Believe it or not, the text editor holy war (as it has become known) has gone on for decades and is amazingly even more heated than the Linux vs Windows debate. In fact it has become so heated that Richard Stalman (the creator of Emacs and the founder of the GNU Free Software Foundation) dresses up as St. Ignucius from the “Church of Emacs”. He has stated many times that “While vi is the tool of the devil” (vi being 6 in roman numerals) “using vi is not a sin but a penance”. Of course the vi crowd weren’t going to take that sitting down and formed the “Cult of vi”. One of emacs strongest features is that you can write code to make it do practically anything you could imagine. This has caused the vi crowd to say that “Emacs is a great operating system lacking only a decent text editor!”.

No one really expects this debate to end and although at times can get quite fiery, it is usually conducted in good humour. At the end of the day, the best text editor for you is the one that makes you most productive and the one that you are happiest using. Still, reading some of the flame wars and reading up on its history can provide good entertainment for those looking for something to do…

Starting Out with Nano

We’re starting out with nano for the simple reason that it’s really easy to use and doesn’t take much explaining. You can quite literally do everything you need to in nano and while you might be able to do it faster in another editor, nano will help you get the job done just fine.

Nano can be run by using the nano command. Okay, no surprises there, but running nano by itself isn’t all that useful. After all you’ve got a text editor now and you want to do some editing. Unless making a few notes, no one ever just writes text without wanting to save it afterwards. Generally then when you open nano you want to open a particular file for editing. That file may or may not exist, but you probably know what it is you want to call it when it comes to pressing the save button. For the sake of our introduction here, we’re going to open nano and tell it that we want to edit test.txt. We can do that with:

[pi@raspberrypi ~] $ nano test.txt

All being well you should get something like this (Figure 6-2):

9781484211632_Fig06-02.jpg

Figure 6-2. Freshly opened nano with a new file

We’ve connected to our Pi using SSH but because nano is a terminal based application, it will look the same regardless of how you run it. One interesting thing about these sorts of terminal applications is that they are sensitive to how big your terminal is. A fixed terminal (such as the physical console) has a set screen size. When you connect via SSH or use a virtual terminal, you can adjust the size of the screen and this will cause nano to resize along with it. This makes it very flexible and can fit in with your needs regardless of the shape or size of your screen.

So What Does this All Mean?

Nano’s screen can be a bit confusing at first (especially the bit at the bottom) but most of the time you won’t actually be paying attention to anything other than your text. In fact all the other stuff melts away in the background. For example on the top left of your screen you can see that we’re running “GNU nano 2.0.9”. Until we came to write this book we had no idea what version of nano we were running and quite honestly until we had to describe it here, if someone had asked us to draw the nano layout from memory we’d have had a pretty hard time doing it. Actually, we wouldn’t have been able to do it at all!

There are two other pieces of information that you can glean from nano’s title bar. Smack bang in the middle is the name of the current file that you’re editing. In our case, it’s “/home/pi/test.txt”. Not exactly earth shattering but it’s quite common to be working on multiple windows at once and being able to quickly get your bearings can come in handy.

The third piece of useful information is whether or not the file has been modified, that is, are there any unsaved changes. This can come in handy too because although you could just simply write the file again, sometimes if you have edited the file from another location, you’re not sure about the changes you’ve made, and you just want to know whether you have any changes that weren’t reflected in the one you’ve been editing. It’s also useful for simply jogging your memory and reminding you to save your work. To see what this looks like, just press the space bar to make a change (Figure 6-3):

9781484211632_Fig06-03.jpg

Figure 6-3. Modified file in nano

That’s pretty much it for the title bar. At the bottom of the screen there are actually two sections. The first one is the status line which shows you important information (right now it’s telling you that it’s a new file) and the second one is the shortcut or menu bar. We’re not going to say much more about the status line as it’s pretty much self-explanatory. Anything of importance that you need to know, nano will put it there. Of much greater interest (and in fact the key to using nano) is the shortcut bar. Let’s take a closer look at it here (Figure 6-4):

9781484211632_Fig06-04.jpg

Figure 6-4. The shortcut bar

When you’ve been working in Windows or on the Mac, you’ve probably reached the point where rather than using the mouse to copy and paste things, you instead use the keyboard combinations. On Windows you would use the control and c keys and on the Mac it would be the command key and c. When you use more than one key in concert with another, you end up with a key combination. Well nano works in a very similar way but rather than copy and paste, all of its key functions are driven with key combinations. Because it would be somewhat difficult to remember all the possible options available (although the ones you’ll use on a frequent basis will soon be committed to your long term memory), nano displays them in the shortcut bar. Actually it only shows the most common commands but we have never needed to stray away from these.

To make use of any command you need to use the correct key combination. You can find which combo you need by looking at the shortcut bar. A short hand way of writing “control key” is to use the carat or “^” symbol. Looking at the shortcut bar you can see that if you want to get help, you need to use “^G” or in other words, hold down the control key and press the G key.

Saving Your File

Saving a blank text file is pretty boring and it’s hard to tell if it saved correctly if all you have is a space character. We’re going to go for an old favourite here and punch in “Mary had a little lamb”.

Unlike some editors (most notably vim which you’ll come across later), nano doesn’t have the concept of different modes. That is, when you type into nano that will be interpreted as text to put into the file. Vim on the other hand starts in command mode and if you just start typing, you will get some interesting results. As you might expect, pressing enter after each line will take you to the beginning of the next line. After typing in the nursery rhyme you should get something like this (Figure 6-5):

9781484211632_Fig06-05.jpg

Figure 6-5. Mary had a little lamb, nano style

We’ve shrunk nano’s window down a bit so that we don’t take up vast quantities of paper with blank white space. It also acts as a pretty good example of why you might want to resize a window and how it looks when you actually do. In this case everything looks just fine although admittedly for writing anything of a reasonable length you’d need something a bit bigger than this.

You may have noticed that the status line seems to have disappeared. This is because the file stops being a new file once any content has been added to it. Our modified warning is still up in the top right hand corner though. It’s time to get rid of that and get Mary safely on to disk.

Looking at the shortcut bar you can see the options we have available to use. The most common ones you’ll use are “WriteOut” which really just means “Save File” and “Exit”. Exit actually doubles as WriteOut because if you try to exit nano with unsaved changes, it will ask you if you want to save your changes.

Let’s start with the WriteOut command. Hold down the control key and press the O key. Nano should now look something like this (Figure 6-6):

9781484211632_Fig06-06.jpg

Figure 6-6. Using the WriteOut command

You’ll notice that we have two changes here. The first is that our status line has made a come back. This time it’s asking for information or at least it wants us to confirm it. Now that it’s time to save the file, nano is asking us to confirm what the name should be. As we passed it a name when we originally started nano, this is the name that nano will provide by default. If we press the enter key now, it will save the file but before we do that, let’s take a look at the shortcut bar.

You can see that it’s changed to a whole new set of options. This is because the shortcut bar is actually contextual, that is it will show you the most relevant things based on what it is you’re doing at the time. These options are only useful (or even available) when saving a file and so this is when you get to see them. We’ve never actually had to use any of these options apart from Cancel (when you suddenly decide that saving is not what you wanted to do at all).

Okay, back to saving the file. If you like you can change the name that the file will be saved as and nano will not only save it under your new name but will continue using that name when you go back to editing which is the same file and you should get a message like this (Figure 6-7):

9781484211632_Fig06-07.jpg

Figure 6-7. File has been written to disk

You can see that the shortcut bar has gone back to its usual look and we have a new message in our status line. You’ll also have spotted that the Modified status has vanished. So far so good.

Let’s quickly look at what happens if you try to exit nano whilst you have an edited file (Figure 6-8):

9781484211632_Fig06-08.jpg

Figure 6-8. Exiting before saving

All we did here was add a signature to the file (although admittedly it probably wasn’t Mary who wrote it) and then tried to exit nano by using control and X. This time the status line gives us a scary warning and the shortcut bar gives us a somewhat reduced number of choices. We can say yes in which case nano will save the changes before it exits or we can say no in which case nano will still exit but we will lose all the changes we made since the last time we saved the file. We can also think better of exiting and change our minds. In this case we can use control plus C to cancel our exit request which will just take us back to nano.

Moving Around in Nano

You can move around your text just by using the cursor keys as you’re probably used to from your word processor of choice. In fact the only reason we mention this here is because some editors don’t use those keys at all because they take your hands too far off the home row (that is, they’re slow to use because you have to move your hands a long distance to reach them). So rather than explaining cursor keys, we’ll show you the two features we use most in nano which are both coincidentally related to finding things.

The first thing you will probably want to use is the search feature which is somewhat oddly named as “Where Is” under nano. We can issue that command by pressing the control and W keys to get to the next step (Figure 6-9):

9781484211632_Fig06-09.jpg

Figure 6-9. Searching for some text

Once again we have some new options available to us. The most common task though is to simply find a word. So let’s search for Mary and see what happens (Figure 6-10):

9781484211632_Fig06-10.jpg

Figure 6-10. Nano found Mary

After pressing the enter key, nano will try to find the text you searched for. In our example, we were already at the end of the file and that’s why you can see “Search Wrapped” in the status bar – nano reached the end of the file and wrapped around to continue the search from the beginning. This is a really handy feature!

It’s quite common that there will be more than one occurrence of the word that you’re looking for. If you wanted the second Mary, you would want to repeat your search. You can do this by just pressing control and W and then immediately pressing the enter key. Nano remembers what you searched for last time and if you don’t supply a new word, it will simply search again with the old word. This means you can easily cycle through the document to find the specific entry that you’re looking for.

The last feature that we’ll cover is a slightly more specific form of search. Rather than searching for a word, we want to go to a specific line number. In day-to-day text editing this is not something that you’ll actually do all that often. However when you start writing scripts and they generate errors, you will generally be told which line that error occurred on. For short programs it often doesn’t matter but if you’re building something fairly epic, you’ll want to be able to get to the line quickly. This is true even in medium length programs because if you have a particularly tricky problem, you’ll have to keep revisiting a specific piece of code and you certainly don’t want to have to use the cursor keys to find it each time.

To go to a specific line number, you need to start the search as you did before by using control plus W but rather than typing any text, you should then do control + T. This will change the status line to read (Figure 6-11):

9781484211632_Fig06-11.jpg

Figure 6-11. Go to a specific line number

All you have to do here is enter the line number that you want to go to and press enter. You can also see there are some other useful options here that allow you to go to the start of the file and the end of the file respectively. You can also press command and T to go back to searching for text or you can press command and C and cancel the search.

Wrapping Up Nano

That’s all we’re going to cover for nano but as you can see, even the limited amount of functionality we’ve covered has already given you the ability to edit configuration files or even compose your own book. Nano is great for these kinds of tasks where you don’t want distractions and you just want to get the job done. As it happens a good deal of this book was written in nano so it just goes to show that this tool is certainly not just a toy! That being said, let’s move on now to look at what the vim editor can offer you instead…

Getting Started with Vim

Vim is a bit more advanced than nano. Whereas nano was specifically designed to be simple, vim is designed to be a fully featured environment for doing all sorts of tasks. You can even integrate other applications (such as the shell and source code control) directly with vim and this means you can do huge amounts of work without ever leaving your text editor.

The downside to this raw power is that you’re going to have to learn how to use it. Unlike nano which is basically ready to use right away, vim has the concept of modes. Generally speaking you’re either in the normal or insert modes and those are the ones that we’ll focus on in this section.

However we do want to point out that even though we use vim ourselves on a regular basis, we’re not what you would call vim experts. We know how to use the functionality that helps us with our work, but there’s a huge number of features that we don’t use or even know about. As this is just a primer on vim, we don’t feel that this is an issue, but if you think vim is the tool for you, there are a wealth of books dedicated solely to vim as well as numerous video tutorials on some of its more advanced and powerful features.

Rather than having to type in yet another poem, let’s give Mary an encore and bring her back to the stage with vim:

[pi@raspberrypi ~] $ vim test.txt

Needless to say, starting vim is as straight forward as starting nano, but it does look a little different once it has started (Figure 6-12):

9781484211632_Fig06-12.jpg

Figure 6-12. Starting up vim

Gone are the nice headers, status lines and shortcut bars. In the land of vim, like Linux itself, we’re expected to know what we’re doing. In the bottom left of the screen you can see the name of the file that we’re editing. Next to that we have 6L which tells us how many lines are in the file followed by 115C which tells us the number of characters. On the other side of the screen we have another useful piece of information 1,1. This tells us the line that we’re currently on and the column that we’re in. At present it is telling us that we’re on line 1 and in the first column. That makes sense because we only just opened the file and if you look at the cursor, sure enough we’ve sitting on top of the first M.

Image Note  Depending on the version of vim and how it is configured, it will usually take you to the location you were at when you last stopped editing that file. This is really useful when programming because it gets you immediately to where the action is.

You can also see seveal lines of tildes “~” beneath the last line in our file. These are here to remind us that although the screen is a certain size there is no content below Mary. This is especially useful when doing certain types of programming and you want to make sure there’s no additional white space. It’s really just a visual clue and won’t get in your way.

Vim’s Modes

Vim comes across as being a bit querky because unlike word processors and more basic text editors, with vim you can’t start typing right away. This is because vim has different modes or personalities. When you first start vim, it is in command mode. Unlike nano where you give commands by using key combos, vim has a wide range of commands that are single or double letters. You might think that this would be hellishly confusing and well, you’d be right. Once you know the magic keypresses to make vim do your bidding, then you’ll love this way of controlling your text editor. Until then however it’s likely to drive you to distraction.

So let’s get out of command mode and into slip into something more comfortable. We can replicate a nano-esque environment in vim by pressing the ‘i’ key. This will take us out of command mode and place us in insert mode. You can tell when you’re in this mode because you get -–INSERT—in the bottom left hand corner (Figure 6-13):

9781484211632_Fig06-13.jpg

Figure 6-13. Vim in insert mode

At this point you can move around your text file just like you did with nano. The cursor keys work as expected and you can add and delete text as you did under nano. The differences start when you want to do something other than writing text though. How do you save your changes?

Saving Your Changes

To save your changes in vim the first thing you need to do is exit from insert mode. This takes you back to normal mode where you can issue commands and consequently where you can save your document. First though let’s change the signatory to say John instead. This will give us the much-needed change for the document. To actually save the document we use this command:

:w

The command really is a colon followed by a lowercase W. Vim is case sensitive so if you tried to do: W you would get an error message that it isn’t valid command (Figure 6-14):

9781484211632_Fig06-14.jpg

Figure 6-14. Whoops, W isn’t a command

There’s no need to panic though, just try the command again and you’ll be fine (Figure 6-15):

9781484211632_Fig06-15.jpg

Figure 6-15. :w on the other hand works like a charm

If you wanted to change the file name whilst you were saving, you can simply type in the file name you want to use after the command like so:

:w test2.txt

This will then save the changes to the new file name and will then continue to edit the new file.

Getting Out of Vim

This leaves us with just one more feature to bring you to the same basic level that you had with nano (we’ll cover searching in just a moment). Once you’ve done all your editing and you’ve saved your files you’ll want to exit. The command for this is:

:q

As long as you haven’t made any changes, vim will immediately exit and you’ll be back at the command line. However if you had made some changes and you try to do this, you’ll once again catch the wrath of vim (Figure 6-16):

9781484211632_Fig06-16.jpg

Figure 6-16. To quit without saving you’ll need an override

Fortunately vim has already told us how to fix the problem, but basically if you want to quit without having your changes saved, you’ll need to explicitly tell vim that’s what you want to do with:

:q!

And that’s all there is to leaving vim!

Searching in Vim

In this section we’re only going to cover the basics and show you how to do the same sort of searches that you did in nano. In actual fact vim has very advanced search capabilities (you can use regular expressions for a start – see boxout) but while you might come to depend on these features as you become more advanced in your usage, you’ll still probably find that you spend most of your time doing the simple things.

To search for a word in vim, all you need to do is prefix it with a forward slash. To give this a try, whilst in command mode (tap the escape key twice to ensure that you’re in the right mode) type:

/Mary

This should then find all instances of Mary and highlight them for you (Figure 6-17):

9781484211632_Fig06-17.jpg

Figure 6-17. Vim found Mary

You can see the “search hit BOTTOM, continuing at TOP” message, which is equivilant to nano’s “Search Wrapped”. One thing to watch out for with vim is that because it uses regular expressions for searching, it’s also case sensitive by default. That means if you search for mary rather than Mary, expect to receive a complaint (Figure 6-18):

9781484211632_Fig06-18.jpg

Figure 6-18. Vim can’t find mary

One area that vim has over nano is how to do repeated searches. To move to the next search result, all you need to do is press the ‘n’ key. In our example text above, if you search for Mary with /Mary and then keep pressing the ‘n’ you will see vim will cycle through the search results for you. We can’t really demonstrate that affect in print, but it’s a nice distraction for a few seconds if you’d rather not be doing something else. If you’d like to search in the opposite direction (i.e. towards the top of the file rather than the bottom) simple use a capital ‘N’ instead.

REGULAR EXPRESSIONS

Regular expressions in the right hands are like magic. They slice through complex text processing tasks like a hot chainsaw through warm butter. They are also frequently used to give system administrators bed-wetting nightmares and to scare small children. Regular Expressions are very powerful once you know how to use them but boy does that power come with a cost. Be that as it may, a basic knowledge of regular expressions will be very useful to you and you can use them directly in vim for searching, replacing and otherwise manipulating your text.

We don’t have enough space to go into regular expressions here (often referred to solely as regex) but there are some fantastic resources available on the Internet to get you started, not to mention complete books on the topic. A great starting place is Jan Goyvaerts’ website http://www.regular-expressions.info/ . Not only is this site full of useful and helpful information (it is very often our first port of call) but Jan has also written some very powerful software. We bought RegexBuddy many years ago and it’s still our first port of call when we’re trying to debug some complicated regex. If you want a simpler tool for testing out your regular expressions, check out http://rubular.com/ which does real time regex parsing in Ruby.

The last thing we covered in nano was moving to a specific line number. This is actually much easier in vim, probably because it’s something that programmers have to do all the time. To jump to a specific line number, all you need to do is place the line number after the colon. For example to jump to the 5th line all you’d need to do is this:

:5

Once you hit the enter key, you’ll be taken directly to the 5th line. As before this feature isn’t particularly useful for normal editing, but it comes very much in handy when you’re fiddling about with a program that simplify refuses to work the way you know it should!

Moving About in Vim

Although we’ve already shown you how to move around your text file, we haven’t been leveraging the power of vim. Vim provides additional commands that can allow us to navigate through text more quickly.

In command mode you can still move around your text using the cursor keys, which is nice and convenient. In effect you can do the same thing using two other commands, the ‘h’ and ‘l’ keys. The h key will move the cursor back one character and the l key will move the cursor forward one character. Admittedly that’s not very exciting, but we can now introduce the ‘b’ and ‘w’ commands. They work just like the previous commands only rather than stepping back just one character, they jump to the beginning of words. Suddenly that’s more useful because now if you have a long line of text rather than pressing and holding down the cursor key for extended periods of time (tempting though isn’t it?), you can greatly speed up the process by hopping a word at a time.

We can take this one step further though. If you want to jump to the beginning of a line you can press the ‘0’ (zero) key. To get to the end of the line, you simply use $ (in our case that means holding down the shift key and pressing the 4 key). This is surprisingly useful because there will be lots of times when you want to get to either the beginning or the end of the line and now you can do so with a single key press.

Let’s put this in a table to make it a bit clearer:

Tablea.jpg

So what we have now is a progressive way to move our cursor from one end of the line to the other. No longer do we have to fiddle about with the enter or back space keys or fall asleep waiting for the cursor to trundle across the screen. That’s just the beginning though because these keys can be used for a lot more than just moving around your file, they can also be used to specify the scope of the commands you feed to vim.

Deleting in Vim

To delete a single character all you need to do is press the ‘x’ key. This will remove whichever letter happened to be under the cursor at the time. This is sometimes useful in its own right (usually when tweaking a typo) but it doesn’t really offer you any great advantages over dropping into insert mode. The ‘d’ key however provides a very powerful delete command, that you can now combine with your newly acquired knowledge of moving the cursor to do some pretty impressive things.

The first delete command we’re going to try is ‘dd’. Let’s start out by deleting the first line in our file. To make sure we’re all in the right place, use the following command to get back to the first line:

:1

Now we’re going to delete the current line by typing:

dd

Your poem should now be somewhat shorter and look like this (Figure 6-19):

9781484211632_Fig06-19.jpg

Figure 6-19. Deleting the first line

Now that we’ve ruined our poem, now would be a great time to introduce another very useful feature in vim, the “undo” command. To undo the change we just made, simply press the ‘u’ key and Mary will be restored to her former glory. This not only prevents panic attacks when accidentally deleting the wrong line, but it also means we can delete parts of this line in numerous fascinating ways.

If you have more than one line that you want to remove, you can tell vim how many times you want it to execute a particular command by prefixing the command with a number. For example if we wanted to remove three lines from our poem, we could do this:

3dd

This is equivilant to pressing the d key six times and gives you this happy result (Figure 6-20):

9781484211632_Fig06-20.jpg

Figure 6-20. Deleting three lines in one go

You can see in the bottom left corner that there are now “3 fewer lines” just as we’d hoped. Let’s restore Mary with the ‘u’ key and try something else. With our cursor at the beginning of the first line, try executing this command:

dw

This command combines the delete command with movement commands that we saw earlier. In this case we combined it with ‘w’ which means “one word to the right”. We can see the effect of that command here (Figure 6-21):

9781484211632_Fig06-21.jpg

Figure 6-21. Deleting a single word

Rather than moving the cursor itself, we have effectively selected text that we wanted to delete. In this case, ‘d’ will start deleting from the cursor’s current location, up to the first letter of the next word. We could have achieved this effect easily enough simply by pressing the ‘x’ key multiple times, but using ‘dw’ is clearly faster and more precise. Let’s take this to the next level again and combine what we know. We know that we can make vim execute a command multiple times by prefixing the command with a number. We also know that we can combine the ‘d’ command with ‘w’ to delete a complete word. Let’s revive Mary (another press of the ‘u’ key) and try this new improved command (Figure 6-22):

2dw

9781484211632_Fig06-22.jpg

Figure 6-22. Deleting two words at once

Well isn’t that interesting? We’ve been able to combine a serious of commands to express some reasonably complicated tasks. You can of course combine these in any way. For example if you wanted to delete everything to the end of the line, you could use d$. If you wanted to delete everything from the start of the line, you can use d0. It’s being able to combine commands in this way that makes vim such a powerful tool for working with text. Although these features are of fairly limited used when working with English prose, when you start working with programming languages, they become very useful indeed.

Misc Little Commands

Before we move on to look at some of the features of Vim’s visual mode, we’re going to provide a very quick overview of some other simple commands that will come in handy. The ‘i’ enters into insert mode but sometimes you want to write immediately above or below the current line. You can get this affect by using O and o respectively. These will both insert a new line and then switch to insert mode. Sometimes you don’t need to actually edit the content of a file but you just need to change a single letter. This could be because of a typo or maybe you just want to increment a number. You can do this with the ‘r’ key. This allows you to replace the character under the cursor with any other character. Simply press ‘r’ and then type the character you want to replace it with. Simple but very effective!

Visual Mode

Visual mode is not something we use very often ourselves but when we do use it, it often saves us a huge amount of time and effort. This mode allows you to select or highlight blocks of text for further processing. This is akin to highlighting text with your mouse in a word processor. There are two ways you can enter visual mode, by pressing either the ‘V’ key or the ‘v’ key. If you use the upper-case V, you will be able to select a block of text based on lines. With the lower-case v, you gain extra precision as you can select based on single letters rather than entire lines. The overall result is the same and the option you choose depends only on which one would be most convenient to you.

So what exactly can you do with visual mode? Well it really doesn’t do anything in and of itself, it just provides an easy way for you to tell vim what text the following command should be applied to. In keeping with our previous examples, let’s select a chunk of Mary’s poem. You don’t need to highlight the exact text that we have, but try to get a fairly random chunk (Figure 6-23):

9781484211632_Fig06-23.jpg

Figure 6-23. Highlighting text in visual mode

As you can see from the highlight, we used the lower case ‘v’ option as we wanted to highlight within a particular word. There’s no real reason for that apart from a sense of the dramatic, so it could easily have been a bunch of lines selected with ‘V’. Now let’s apply our favourite command, the delete command. By pressing ‘d’ you will find that the highlight text magically disapears. In this case you don’t need to provide additional information to vim to tell it what to delete because in effect you’ve already told it by highlighting the text in the first place.

Of course you can do other interesting things apart from deleting text (though deleting text is fun). For example, if you want to indent the first two lines of the poem, you can highlight the first two lines with V and then use the greater than and less than signs ( > and < respectively) as appropriate. We can’t show you how that would look in print (honestly moving huge chunks of text back and forth is surprisingly theraputic) but we can show you the end result of this command (Figure 6-24):

9781484211632_Fig06-24.jpg

Figure 6-24. Indenting highlighted text

There is one more terribly useful feature that we haven’t covered yet that works very nicely with visual mode - copy and paste.

Copy and Paste Vim Style

Copy and paste in a terminal is something of an iffy proposition. The reason for that is an application running in the terminal effectively lives in its own little world. If you copy text from the terminal on your laptop for example, that text is copied into your laptop’s clipboard. The remote application (in this case vim) has no idea that you did that. Likewise if you paste content in to vim from your laptop, vim will simply receive it as a set of key strokes, it won’t have a clue that it came from a clipboard. Generally speaking this is okay. If you just want to move a bit of text about, then using the clipboard in this way is probably fine.

There are times when this doesn’t do what you want. For example, if you have a split screen and you have two files side by side and you want to select the first paragraph on the left, you’re now a bit stuck. The terminal just shows you a representation of what’s on the server, it’s just a display and as such the terminal has no real understanding of what it’s displaying. If you try to copy and paste the left hand side, you’ll find the right hand side comes along for the ride. That’s far from ideal (not to mention highly irritating).

Another issue you might come across is that you might want vim to do something with the text. If you just want to paste it once, no big deal, but what if you want to paste exactly 10,004 times? Vim can’t help you there because it has no concept of your local clipboard. You’ll find that when these issues do crop up they’ll be fairly niche and you can work around them. However it is likely to really irritate you because you will think “if only I could just copy this text!” whilst you’re sat there trying to work around the problem.

What we need then is a remote clipboard, somewhere for the remote application to store data for processing. There’s no standard for this as such but many terminal based applications offer a solution and in the case of vim, it’s the yank and paste feature. To yank some content you need to use the ‘y’ key. This takes the same modifiers that the ‘d’ command uses so you can quite happily copy an entire line with ‘yy’ (remember, the letter just doubles up), and a single word with ‘yw’. Also like the delete command we can also use this with the visual mode.

First, simply highlight the text that you want to copy. For simplicity, let’s go for the top two lines again. Once you’ve highlighted that with the ‘V’ key, press the ‘y’ to yank it into the clipboard. That’s phase one complete, now all we have to do is paste it back into our file. There are two ways you can use the paste command with either ‘P’ or ‘p’. As with the ‘V’ and ‘v’ commands, the upper and lower case versions are usually related in some way. In this case, the ‘P’ key inserts the content before the current line whereas the ‘p’ key inserts it after. Feel free to move your cursor to any location location in the file before hitting one of those keys. The effect is really what you’d expect and vim will just paste content in. You can of course combine these commands with the numeric prefixes to repeat the number of times something is inserted. Here’s what happens if you end 40p (Figure 6-25):

9781484211632_Fig06-25.jpg

Figure 6-25. Mass pasting

Although you don’t know it yet, you actually learned to cut as well as copy text. Whenever you use the ‘d’ key, you delete the text from the file, but a copy is placed in the clipboard. If you select a line and delete it with ‘dd’, you can restore it with ‘P’. Bear in mind that if you use the ‘p’ key instead, because you’ve removed the line, you’ll actually be inserting the original line after the line you’re currently on. If you want to restore it to its original location, you must use the ‘P’ key to paste before the current line.

Summary

In this chapter we’ve looked at what separates a text file from a binary file and why text files are the lingua-franca when it comes to configuring software. We’ve covered two of the key text editors that you are likely to come across in your travels and we’ve given you a good grounding in both of them. Certainly we have not been able to show you everything that is possible, but now you should be in a good position to explore and try new things yourself.

In the next chapter we’re going to cover the BASH shell and show you some of the more important things that a system administrator needs to know…

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.55.42