Searching and Replacing in Vim

45 minutes
  • 3 Learning Objectives

About this Hands-on Lab

Searching for text is more efficient than scrolling and looking for a phrase or setting. Being able to find and subsequently replace an instance of a word or phrase, or many instances, is an important skill for anyone who works with large text files, be they configuration, code, or prose.

In this hands-on lab, you will practice finding the next instance of characters, a word or phrase, either forward or backward. You’ll also practice searching and replacing text using various helpful options, and also how to easily and economically repeat previous actions for smoother editing.

Finally, you’ll practice on a small scale the replacement of a given string in multiple files using scripting and the `ex` mode of Vim.

Learning Objectives

Successfully complete this lab by achieving the following learning objectives:

Search for Characters and Strings, and Search for Words in Specific Positions
  1. Open the Vim editor:

    vim
  2. Create a working file (and open it for editing) with:

    :help windows
    :w ~/vimwindows.txt
    :q
    :e ~/vimwindows.txt
  3. Go to the top of the file with gg and then navigate to the line that starts with

    Editing with multiple...
  4. With the cursor on the E in Editing, find the next occurrences of an e by pressing:

    fe
    fe
  5. Attempt to find the next occurrence of the | symbol by pressing:

    f|

    Note: The f command can only find on a line, not across multiple lines.

  6. Find a string (and move to a line) with:

    /The
    ENTER
    n       (To go to the 2nd found occurrence)
  7. Now try the f| command again:

    f|
    f|  (to go to the next |)
    F|  (to go to the previous |)

    Note: This will work with most any character or numeral.

  8. Go to the top of the file again with gg.

  9. Find a string that is at the end of a line with:

    /window.
    ENTER
  10. Then find a numeral only at the beginning of a line with:

    /^1.
    ENTER
    n
  11. This finds both the 1. and the 10. strings because the . is being used to mean any character, not specifically a period. Redo the command and make sure the . character is not being used as a Regular Expression with:

    /^1.
    ENTER
  12. This will result in finding the line beginning with:

    1.  Introduction
  13. Return to the top of the file with gg

  14. Search for all instances of the string the with:

    /the
    ENTER
  15. Make your search results more visible with the command:

    :set hlsearch
  16. Now set your highlight to a more pleasing color schema with:

    :highlight Search ctermbg=grey ctermfg=green
  17. Next, return to the top of the file and search for the strings that start with the, using:

    gg
    /<the
    ENTER
  18. Now search for strings that END with ing:

    /ing>
    ENTER
  19. Finally, search for the separate word a with:

    /<a>
    ENTER

    Note: This will show only the word a, not a in as a part of other words or strings.

Remember: If you can find it, you can do something useful like replace it…

Search and Replace Text, Then Search for and Delete Text

Note: You must have done Steps 1 and 2 in Task 1 before you are able to do Task 2.

  1. Return to the top of the file with gg.

  2. Now turn off search highlighting with:

    :set nohlsearch
  3. Search for the string window and replace it with WINDOW with the substitute command:

    :s/window/WINDOW/

    Note that only a single instance of window was replaced, on the current line.

  4. Search for the string window and replace it with WINDOW on all lines, but only the first instance on a line with:

    :%s/window/WINDOW/
  5. Note that the first instance was replaced, but not all instances, and remember the number of substitutions.

  6. Return to the top of the file with gg and restore the file to the original state by pressing u until you get the message:

    Already at oldest change
  7. Run the substitute command again with the g addition to replace all instances of window with WINDOW with:

    :%s/window/WINDOW/g
  8. Note the larger number of substitutions made.

  9. Restore the file to it’s original state by pressing u until the get the "oldest change" message again.

  10. Repeat the previous substitute command by picking it from the history by pressing:

    q:  (No, it's not a typo...)
    k   (or the up arrow)   
    A   (to add to the command)
    %s/window/WINDOW/gc (Add the c)
    ENTER
  11. Use the prompt interface to experiment with the confirmation actions:

    • y Substitute match
    • l Substitute match and quit
    • n Skip match
    • a Substitute this and all other matches
    • q Quit substituting

    Note: Ensure that you use either a for all, l for last, or q to quit the substitute command instance.

  12. Restore the file to it’s original state by pressing u until the get the change message again, then gg to go to the top of the file.

  13. Search for and delete all instances of the word buffer with:

    :%s/buffer//g

    Note: Notice the large number of deletions made,

  14. Now restore the file with u, and gg, and delete just the instances of buffer that are a separate word with:

    :%s/<buffer>//g

    Note: Notice the lower number of deletions made.

  15. Next, restore the file with u, then gg and delete just the instances of the word buffer that are followed by a . (the period character) with:

    :%s/buffer.//g

    Note: Notice that many less deletions are made,

  16. Lastly, restore the file with u and do the deletion for just the first 50 lines of the file with:

    gg
    :1,50 s/buffer//g

    Note: Notice the small number of deletions that occurred due to the line range restrictions.

  17. Exit the demonstration file without saving any changes with:

    :q!
Search and Replace in Multiple Files

Note: You’ll be making a update directory, copying some HTML files into it, and then writing two scripts in Vim to make mass changes in those files.

  1. As cloud_user, create a subdirectory in your home directory with:

    mkdir ~/updatehtml
  2. Change into the updatehtml directory with:

    cd ~/updatehtml
  3. Copy a couple of HTML files to the new subdirectory for use in this lab with:

    cp /usr/share/doc/nano/*.html .

    Note: We’ll be replacing some tags with others for the sake of formatting, according to a directive from the Design Team.

  4. Verify the number of <h2> tags in the target files with:

    grep -w h2 *.html
  5. Then run the command again and get a line count with:

    grep -w h2 *.html | wc -l
  6. Note this number, for later comparison.

  7. Open a new buffer/file in Vim that will be the include file for our update script with:

    vim update.vim
  8. Enter Insert mode with the i command and put the following in the body of the file:

    %s/h2/h3/gi
    write
    quit
  9. Save and exit the file with:

    :wq
  10. Open another new file in Vim that will become the update script for our replacement operation with:

    vim updatehtml.sh
  11. Enter Insert mode with the i command and put the following in the body of the file:

    #!/bin/bash
    for file in *.html; do
        vim -e -s $file < update.vim
    done
  12. Save and exit the file with:

    :wq
  13. Confirm the number of <h2> tags in the target files again with:

    grep -w h2 *.html | wc -l
  14. Run the update script against the HTML files with:

    bash updatehtml.sh
  15. Confirm that the updates happened to the HTML files with:

    grep -w h2 *.html | wc -l
  16. If your count is 0, congratulations! If not, please check your script and include file for any syntax or capitalization errors. Ensure that the files below are all in the current directory and that it’s the ~/updatehtml directory:

    faq.html
    nano.html
    update.vim
    updatehtml.sh

Remember: You can change the search and replace strings in the update.vim include file to search for and replace anything in any file you want to.

Additional Resources

While observing others more familiar with Vim, you notice they seem to be able to very quickly find what they are looking for, and in some instances you see them do a search and replace that looks complex, but accomplishes a lot once they have it properly formed.

You want to possess those skills, so you get a guide and sit down with some text and html files and start working out how to find things. You do some more complex searches, along with replacing, and then see how to search/replace in multiple files in an automated fashion.

You are immensely pleased with your progress.

What are Hands-on Labs

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Sign In
Welcome Back!

Psst…this one if you’ve been moved to ACG!

Get Started
Who’s going to be learning?