How to grep and replace a word in a file on Linux?

LinuxOpen SourceOperating System

While there are plenty of ways to print and make use of specific words from a particular file in a Linux directory, when we talk about grepping a particular word and then replacing it with some other word, then we will need to mix certain Linux utility commands.

The two Linux utility commands that we must be aware of are −

  • find − used to locate a particular file or directory

  • sed −short for stream editor and is used to perform functions like searching, editing and replacing.

In order to solve the problem of grep and replace a particular word we will make use of a combination of a command that involves both the above commands.

Consider we have a text file named textfile.txt in which the following text is present −

this is a simple file

Now, we want to replace the text = simple to something like text = not a simple. In order to do that we will first locate the file, then we will use the exec utility command to tell Linux we want to execute something, followed by the sed command that will help us to grep and change the string in the file.

Run the following command in your terminal −

find textfile.txt -type f -exec sed -i "" "s/sample/not a sample/g" {} \;

After running the file, your content inside the textfile.txt should look something like this −

this is a not a sample file

Problem solved, but wait, if you are on a mac os, then in order to achieve this output you will need to export two environment variables or you can place them either in the ~/.bashrc or ~/.zshrc.

In the code below, you can see the different environment variables that are present in my ~/.zshrc −

immukul@192 linux-questions-code % cat ~/.zshrc
export GOPATH=/Users/immukul/go_projects
export NDHOME=/Users/immukul/Downloads
export GOTRACEBACK=all
export GOROOT=/usr/local/go
export LC_CTYPE=C
export LANG=C

By setting the LC_CTYPE to C we are telling the Linux that each byte in strings to be its own character without applying any encoding rules.

Please notice the last two variables that are there in the ~/.zshrc file output above, you only need to put them in either your ~/.bashrc or ~/.zshrc file and you are done.

Updated on 30-Jul-2021 08:39:11