How to use the sed command to replace a text in files present in a directory and subdirectories?

LinuxOperating SystemOpen Source

Let’s consider a case where we have two directories, say, d1 and d2 and both these directories contain some files, which may be the same or different. Now we want to make use of the sed command to replace a particular text that might be present in some of the files in either the d1 directory or the d2 directory.

In order to do that, we must be familiar with the sed commands, as the sed commands can be used to solve the above problem.

Let’s first explore the sed command, which is short for stream editor. This command is used to perform different functions like find, replace, insert and many more on a particular file.

Let’s explore the case where we have two directories d1 and d2 and both these directories contain some files in them.

Consider the terminal output to depict these two directories shown below −

immukul@192 linux-questions-code % ls -ltr
total 0
drwxr-xr-x 5 immukul staff 160 Jul 5 20:03 d1
drwxr-xr-x 4 immukul staff 128 Jul 5 20:03 d2

Now the contents of the first directory d1 looks something like this −

immukul@192 d1 % ls -ltr
total 0
-rw-r--r-- 1 immukul staff 0 Jul 5 20:03 1.txt
-rw-r--r-- 1 immukul staff 0 Jul 5 20:03 3.txt
-rw-r--r-- 1 immukul staff 0 Jul 5 20:03 5.tx

Now the contents of the first directory d2 looks something like this −

immukul@192 d2 % ls -ltr
total 0
-rw-r--r-- 1 immukul staff 0 Jul 5 20:03 2.txt
-rw-r--r-- 1 immukul staff 0 Jul 5 20:03 3.txt

Now if we print the content of the files that are present inside the d1 directory we will get something like this −

immukul@192 d1 % cat 1.txt
orange

immukul@192 d1 % cat 3.txt

immukul@192 d1 % cat 5.txt
orange

We can see that the files 1.txt and 5.txt contain a string ‘orange’ in them.

Now if we print the content of the files that are present inside the d2 directory we will get something like this −

immukul@192 d2 % cat 2.txt
orange

immukul@192 d2 % cat 4.txt

We can see that the file 2.txt contains a string ‘orange’ in them.

Now we want to replace the string ‘orange’ with ‘apple’ in all the files using a single command and in order to do that we type the following command to the terminal

find ./ -type f -exec sed -i -e 's/orange/apple/g' {} \;

Output

immukul@192 d1 % cat 1.txt
apple

immukul@192 d1 % cat 3.txt

immukul@192 d1 % cat 5.txt
apple

immukul@192 d2 % cat 2.txt
apple

immukul@192 d2 % cat 4.txt
raja
Published on 31-Jul-2021 12:01:57
Advertisements