How to Replace All Occurrences of a Word in All Files in Linux Command Line

Question: How do I replace all occurrences of a word in all the files in the given folder?

Consider a problem scenario where you have a website in which you often refer to the current year. Every year you need to update the year. You can easily find all occurrences in all the files but manually changing the year, one by one, in each file should be avoided.

Solution

So, what do you do? One of the several ways to find all occurrences and then replace the searched term is by using a combination of find and sed commands.

You can easily do so with a single command: In this example, you have 50 web pages in the pages folder. This command will instantly change all occurrences of “2017” to “2018”:

find ~/public_html/my_website/pages -type f -exec sed -i 's/2017/2018/g' {} \;

To make the above example a bit more generic, here’s what you need to do:

find <path_to_directory> -type f -exec sed -i 's/<search_text>/<replace_text>/g' {} \;

In the above command, replace <path_to_directory>, <search_text> and <replace_text> with the actual data.

Explanation

What you are doing here is that you are using find command to get all the files in the current directories and its sub-directories. The -type f option makes sure that you only get files, not directories.

And then you pass the result of find command using the exec command to the sed command. The sed command searches for the text and replaces it.

The {} \; is part of the exec command. The space between } and \ is mandatory.

This Linux quick tip was suggested by Linux Handbook reader, Jane Hadley. Got a better solution for this problem? Share it in the comments.