Check out a free preview of the full Introduction to Bash, VIM & Regex course

The "Search and Replace" Lesson is part of the full, Introduction to Bash, VIM & Regex course featured in this preview video. Here's what you'd learn in this lesson:

James demonstrates search and replace with Regular Expressions.

Preview
Close

Transcript from the "Search and Replace" Lesson

[00:00:00]
>> James Halliday: Some more fun things, we did combining with deletes. We can also do search and replace. So this should be familiar. It's the same thing we did with Said. That works in VIM, as well. So if we want to search a pattern like, I suppose, we want to search for the word Dog on the current line and replace it with cat.

[00:00:26]
In command mode, you can do :s, have your pattern like dog, and replace it with cat by doing :s. /dog/cat and omit the final trailing slash if you like doesn't really care or you can include it.
>> James Halliday: And when you do just an S by itself just like in said it will find the first instance and replace it.

[00:00:59]
If you wanna do all of the instances on the current line then you can put a at the end, the flag using regx for global substitution. So if I do :/dog/cat, then it should replace all of the dogs on that current line with cat.
>> James Halliday: So I'm gonna add dog a few more times into this file, and then I'll show you how you can do a global substitution, which is pretty handy, I do that a lot.

[00:01:32]
>> James Halliday: Okay, so if you try to do :s/dog/cat/ on a line where there's no dog then it's not gonna replace anything. Pattern not found: dog. So, what you can do is if you do :% s/dog/cat/, then it's gonna search every single line in the file. So if you do that, on very line I replace the first instance of Dog with cat.

[00:02:07]
So there's still dog in the file. If I wanna replace every single instance, I can add g to that substitution, and that will replace every single instance in the file of dog, with cat. There we go.
>> James Halliday: So I'm doing U and Ctrl + R which is undo and redo.

[00:02:28]
So that's kinda.
>> James Halliday: Do you want to show different?
>> James Halliday: Other flags common to regex works, like the iflag, for case insensitivity. Works just the same as it does and said.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now