Open In App

Find and Replace with sed in Directory and Sub Directories in Linux

sed stands for stream editor. It is a basic utility command in Linux that has basic functionality like inserting, deleting, finding, replacing, and searching text strings in a file. But sed is most commonly used for its substitution function i.e find and replace.

Syntax

sed OPTIONS... [script] [input_file]

e.g. 



sed "s/abc/ABC/g" abc.txt

Consider the above example, 

  1. “s/abc/ABC/g” – It is the [script] which specifies what actions are to be performed. 

      2. abc.txt –  It is the [input_file], where the name of the file which is needed to be searched is specified.



Output

 

Find and Replace with sed in Directory and Sub Directories in Linux

Scenario

To demonstrate the example, we created a directory namely, sed_article, which contains a .txt file (file1.txt) and two subdirectories, subdir1 and subdir2, each of which contains one .txt file (file2.txt and file3.txt). 

 

Also, the content of all the .txt files i.e. file1.txt, file2.txt, and file3.txt is kept same for the simplicity. 

 

However, when we need to Find and Replace within directories and subdirectories, we cannot use the sed command alone. It needs to be accompanied by a few other commands, which would include grep, xargs, and the pipe (|) delimiter command.

The command for Find and Replace with sed in Directory and Sub Directories in Linux is as below:

grep -rl ‘bugsyy’ “sed_article/” | xargs sed -i ‘s/bugsyy/BUGSYY/g’

Explanation : 

Basically, -r with grep is used to search for the string recursively, and -l is tag is used for listing the files. But here both the tags will be used together as we need a list of files as output which will be further used as input to the sed command using pipe ( | ) delimiter.

Thus, the grep command with -rl tag search for the string “bugsyy” recursively into the specified directory and then lists the file in which the match is found.

The output for just grep command with tag -rl is as follows :

grep -rl 'bugsyy' "sed_article/" 

 

Now the output from the above command i.e. the list of files that includes the string will be given as input to the sed command using pipe ( | ) delimiter, and the xargs will convert it to the standard input values so as to successfully execute the command.

 

In the above terminal, we first displayed/checked the contents of file1.txt before running the command for finding and replacing the string. And, after the execution, we displayed/checked the contents of file1.txt once more to confirm the changes. So the changes were successful

Recursively, the string “bugsyy” was successfully changed to “BUGSYY” in other subdirectories where the match was found.

Conclusion :

So this is how we can find and replace with sed in Directory and Sub Directories in Linux. In the above methodology, we used the sed command along with grep, xargs, and pipe delimiter ( | ).  

Article Tags :