Replacing a pattern with text in all the files 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's source directory. Using the shell for this is one of the quickest methods out there.
How to do it...
From what we have learnt 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:
$ find . -name *.cpp -print0 | xargs -I{} -0 sed -i 's/Copyright/Copyleft/g' {}
How it works...
We use find
on the current directory to find ...
Get Linux Shell Scripting Cookbook - Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.