- [Instructor] Welcome to the next video of Section Four,
Replacing a Pattern with Text in All Files in a Directory.
In the previous video, we've learned how to remove
a sentence in a file containing a word.
In this video, we'll learn how to replace
a particular text with a new text
in every file in a directory.
There will be numerous occasions when we will need
to replace a particular text with a new text
in every file in a directory.
An example would be changing a common URI
everywhere in a website source directory.
Using the shell for this is one of
the quickest methods out there.
From what we've learned up to now,
we can first use find to locate the files
we want to perform the text replacement on.
Then we can use sed to do the actual replacement.
Let's say we want to replace the text, copyright,
with the word copyleft in all CPP files.
Let's see how it works.
We use find on the current directory
to find all the files of CPP and use print
to print a null separated list of files.
Recall that this helps if the file names
have spaces in them.
We then pipe this list to xargs, which will parse
these files to sed, which in turn
will make the modifications.
If you recall, find has an option minus exec,
which can be used to run a command on each
of the files that find will match.
We can use this option to achieve the same effect
or replace the text with a new one, as follows.
While they perform the same function,
the first form will call sed
once for every file that's found.
While in the second form, find will combine
multiple file names and parse them together to sed.
Awesome!
We've successfully learned how to replace a pattern
with a text in all files in a directory.
In the next video, we'll learn about text slicing
and parameter operations.