Exercise: Macros


Text Objects & Macros
Text Objects
19m 34s
Start course

This course looks at text objects and macros in Vim, both of which are tools intended to help you edit text more quickly and efficiently. Text objects allow you to make changes to words, phrases, and sections of text based on various parameters. We then look at macros, which allow you to repeat preset series of commands in order to save time.

For both text objects and macros, we will walk you through some examples of how they are used in order to give you a practical understanding of them.

Intended Audience

This course is ideal for anyone who needs to edit text files in a command-line environment.


If you want to follow along with the exercises in this course, you should have the Vim text editor installed on your computer.


If you want to follow along with the exercise(s) in this course, you can find the necessary resources here.


The goal of this exercise is to practice creating and using macros. First, start a command line session on your local machine. Next, use Vim to open the macros-practice.TXT file that came in the course downloads. To do that, navigate to the location of the file, and remember, this could be different for you depending on where you extracted the contents of that file. This example assumes the course download was saved into your downloads folder and extracted from there. So, I'm going to change into that directory, then into the Vim class directory, and finally open the file. Let's say you have some old Python code that needs to be updated to work with a new Python interpreter. The print statement was replaced with a print function. This means you'll need to add parentheses to your print statements to make them print functions, and we can do this with a macro. By the way, it's not important to know anything about Python. The goal here is just to give you a practical example for you to practice your Vim macro skills with. So, here's one way to accomplish this task. First, position your cursor on the line we're going to work on, and then what we want to do is start recording into the A register with QA. And we're just going to normalize our cursor position to the beginning of the line by typing 0. Now, we're gonna position the cursor at the next space with F-space. That's a forward search on the same line to the space character. Now let's replace that space with an opening parentheses, which is R open parentheses. Now, we can append a closing parentheses by using Shift A-- Capital A, which depends to the end of the line, and then, use the close parentheses, and press Escape to return to normal mode. Now, we can position the cursor on the next line with J, so the macro can be easily repeated. Finally, type Q to stop recording the macro. Now, let's play the macro back by typing @, A. Now, we can just use @, @ to repeat that macro, and we'll do that, yet one more time, to finish our edits. By the way, I just want to point out that the solution I used here was just one way to accomplish the same task. For example, I use F space to do a forward search, but you might've decided that you wanted to do till double quotes with T double quote. Again, both perform the exact same action, but there are just two ways to do the same thing. As long as you get the desired results you're after, that's really all that matters. Now, let's move down to this next list of items. Let's say you have a list of users and you want to perform the same set of actions on each of those users. One way to accomplish this, is to record a macro that performs the required command for one user, and then apply that macro to the rest of the list. For example, let's say you wanted to run some commands on a Linux system to lock each of the user accounts, and then add those accounts to a text file, named Logged_users.TXT. Of course, it's not important what these commands do; as we're just interested in them, but I wanted to provide you with a practical example. Here's one way to this accomplish this task. First, let's start recording into the B register with Q, B. Next, yank the username into the default register with Y, A, W. start insert mode at the beginning of the line with capital I, and now, type the text P, A, S, S, W, D, Space, Dash, L, Space, and press Escape. Next, start insert mode at the end of the line with capital A, and then type Space, &, &, Space, Echo, Space, Escape. Next, paste the contents of the unnamed register after the cursor position, with P. Continue appending by typing A, and then typing Space, >, >, Space, locked_users.txt followed by escape to return to normal mode. Now, position the cursor on the next line with J, so that this macro can be easily repeated. Now that we're done, we can hit Q to finish recording. If you want to, you can examine the contents of your macro by looking at the B register, and you can do that with ":reg B", and hitting Enter. Let's play back the macro to see if we got it right with, "@B". There are three more users left on this line, so let's just repeat the macro three times with, "3@b". Our next task is to create a macro that changes a series of digits into a United States style phone number. I'll just move my cursor down a few lines here, and press the Z and Enter to move the view up on our screen. Let's start recording into the P register with Q, P. Start insert mode at the beginning of the line with capital I. Now, type in opening parentheses, and then press Escape to return to normal mode. Now, we can position our cursor under the nine by typing L three times. Now, type an a, to a pen text after the cursor and type the clothing parentheses followed by a space and we'll hit escape to return to normal mode on this particular line. We want the cursor to be under six, so we'll just type L three times. And now what we can do is type a, and then a dash two a pin, a hyphen, and press escape to return To normal mode. Now position the cursor On the next line with J so that it's easy to repeat this macro. Finally, we'll type Q to quit recording the macro. You can look at the contents of the macro with redge P and hit enter because there's A long list of phone numbers that scroll off the bottom of your screen. You can't easily know how many lines you need to apply. The macro to, also repeating @ @ could take quite some time. So let's get the range you need to apply the macro to let's turn on line numbering was set And you note that our cursor Is on line 25, and let's just go forward in the file with control F and see where this set of numbers ends and it ends on line 73. So now let's execute the macro over this range using the normal command. So we'll do colon 25, comma 73, which is our range and then we can type the normal command. And then we need to provide the register with @ P and then press enter. I'm just going to use control B here to look at all of these lines. That had phone numbers on them and to make sure that they all look correct and they do okay I am gonna move back down to the next set of lines here and position my cursor here and just press the Z and enter this next set of lines in the file contains system logs from a Linux server. Specifically, these lines are logs of blocked connection attempts by the local Linux firewall. Your goal here is to extract the timestamp the source IP address and the connection attempt and the destination port. So mainly what we're looking to do is to take all this extraneous data, throw it away and then normalize it into a comma separated value line. We'll start recording into the L register with QL, and by the way these registered numbers that I'm picking don't necessarily have to be the ones that you use. For example, I used L here because it makes me think of a log line at any rate. Let's make sure we normalize our cursor at the beginning of the line by typing zero. Now we'll position our cursor on the space just after the timestamp, by typing T W. Now let's delete all the texts up to Capitol SRC equals, and we can do this with D T shift S now we need to get ride of the characters SRC, and we can do that with DW. Next, we can replace the equal sign with a comma by using R comma. Now let's position our cursor after the IP address with F space. And now what we need to do is delete the text up to D P T equals with the Ford search which is a Ford slash D P T, and then press enter. Now we can delete DPT with the DW again we can replace the equal sign with a comma by using R comma. Now the cursor after the port number with F space. Next, we just need to delete the remaining text on the line. And we can do that with capital D now position the cursor on the next line with J so that the macro can be easily repeated. Finally, we'll just hit Q to stop recording the macro. Let's look at the contents of this macro with a reg L as always. There are other ways to accomplish this same task and I'll just leave it to you for you to think about other ways that you can get the exact same result with a different set of commands. Now let's test our macro by typing @ L that looks correct. So let's continue with @ @ and we'll just repeat this until all of our lines here are formatted we'll position our cursor on this next exercise here and hit Z and enter to move this text up on our screen. And I just want to remind you that macros are just a series of keystrokes even though in this exercise you've been working on macros that manipulate single lines. You can also easily manipulate multiple lines. Let's say you want to condense the data. That's contained over two lines onto a single line and let's do this by recording into the C register. So two Q C next let's make sure our cursor is normalized by typing zero, and let's delete the word country with D W. Now we can move down to the next line with J and cut the number into the unnamed registered with the capital. W now we'll move up to the original line with K and paste the number before our cursor position with capital P. And now we can replace the space with a semi-colon by typing R semi-colon. Now we'll go back to the line below a J and then let's delete two lines here with two D D. Our cursor is at the beginning of the next set of data. So we're already in position and we can type Q to quit recording our macro. You can see that there are only four more occurrences of this type of data. So we can just repeat this macro with four @ C let's move down the file a little bit and reposition the view higher on our screen here. You can see that we have a list of a HTML tags and they're all squished on the same line. And our goal is to convert those links to just the domain names. For example, the first one, well we don't want that. Or the A tags. All you want his army on one line let's record this into the Q register with Q Q by the way, I like to use QQ to record a macro that I'm just going to use and then not need again because it's pretty quick to just type QQ. Now, what we want to do for this macro is delete the text up to, and including the add sign. And we can do that with D F @. Now let's just position our cursor under the less than sign with F less than. Now what we want to do effectively is replace this closing A tag with an inner. And so we can do this by using a change motion so we can use C F greater than and then just press enter and press escape. And now we've effectively replaced that with enter since we're in position already for our next set of instructions, we can type Q to stop the macro. If you want to look at the contents of your macro you can use reg Q and there are the commands you recorded into the queue register. Let's run our macro with @ Q and let's just keep using @ @ until all the data looks exactly how we want it keep running @ @ not sure how many there are here. And there we go. If you would like to practice this exercise again you can simply abandon your changes with colon Q !, and pressing enter.

About the Author
Learning Paths

Jason is the founder of the Linux Training Academy as well as the author of "Linux for Beginners" and "Command Line Kung Fu." He has over 20 years of professional Linux experience, having worked for industry leaders such as Hewlett-Packard, Xerox, UPS, FireEye, and Nothing gives him more satisfaction than knowing he has helped thousands of IT professionals level up their careers through his many books and courses.