Replace string contains special character in Vim

Nguyen EngineerNguyen Engineer
2 min read

A Simple Solution to a Tricky Problem

If you've ever tried to replace a string containing special characters in Vim, especially across multiple files, you know it can be a real headache. The usual search and replace commands often fall short, getting tripped up by those pesky special characters.

After much trial and error, I've found a reliable method that makes this task straightforward. Here's how to do it:

  1. First, use fzf's live grep to find all occurrences of your string:

     :Rg "w.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")"
    

    This populates your quickfix list with all matches.

  2. Now, here's the key command that does the heavy lifting:

     :cfdo %s/\V\Cw.Header().Set("Content-Type", "text\/html; charset=utf-8")/w.Header().Set("Content-Type", "application\/json")/g
    

    Let's break it down:

    • cfdo: Applies the command to all files in the quickfix list.

    • \V: "Very nomagic" mode, which treats most characters literally.

    • \C: Ensures case-sensitive matching.

    • \/: Escapes forward slashes to avoid confusion.

  3. Finally, save all your changes:

     :wa
    

And there you have it! This method reliably replaces your string, special characters and all, across your entire project.

No more wrestling with escape characters or pulling your hair out over missed replacements. With this approach, you can handle even the trickiest of string replacements in Vim with ease.

Give it a try next time you're faced with a challenging find-and-replace task. You might be surprised at how smoothly it goes!

0
Subscribe to my newsletter

Read articles from Nguyen Engineer directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nguyen Engineer
Nguyen Engineer

👋 Hi, I’m Nguyen, or you can call me Finn 💾 Vimmer ❤️ Gopher 📍I'm based in Da nang, Vietnam ⚙️ I love working with Go and Typescript ⚙️ I love both building distributed systems and the artistry of creating a single binary that efficiently uses minimal resources to accomplish as much as possible.