Tutorial hero
Lesson icon

Using grep and sed

Originally published June 15, 2023 Time 2 mins

I’ve been using neovim as my code editor for a while now, and every now and then you run into the issue of lacking something a full featured IDE like VS Code provides.

For example, probably the most awkward problem (at least initially) I ran into was how to do a search and replace across an entire project in neovim.

You initially want to reach for something familiar, and sometimes plugins can replicate the typical IDE experience, but usually the answer ends up being more along the lines of: you need to think about this problem from the perspective of using the terminal - not an IDE.

That’s a lot of rambling to get to my main point which is that the answer in this particular case is to become more familiar with the command line utilities grep and sed. Using grep will allow you search for strings across files, and sed will allow you to write changes to those files.

So, here’s an example from today. I needed to update the file paths in a bunch of markdown files in my project. To do this with ripgrep (an alternative to the standard grep) and sed I ran this command:

comman to run ripgrep and sed

This isn’t the prettiest replacement since I am replacing a long file path which requires a bunch of escape characters, but the basic structure is this:

comman to run ripgrep and sed

We use ripgrep with the -l option so that it just returns a list of file names that contain that string. We then pipe that result into xargs which allows us to take the resulting file list and pass it to sed as an argument. The -i option allows for editing the files in place, and then we supply the string we want to find in the files ripgrep returned along with its replacement (the empty string after the -i means we don’t want a backup file created).

It can be a bit to wrap your head around, but the great thing about this is that once you are familiar with these tools you can use them anywhere you need on your entire filesystem instantly from the terminal.

Learn to build modern Angular apps with my course