Replacing a pattern with text in all the files in a directory
We often 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.
How to do it...
We can use find
to locate the files to have text modified. We can use sed
to do the actual replacement.
To replace the Copyright
text with the Copyleft
word in all .cpp
files, use the following command:
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 the files with a .cpp
suffix. The find command uses -print0
to print a null separated list of files (use -print0
when filenames have spaces in them). We pipe the list to xargs
, which will pass the filenames to sed
, which makes the modifications.
There's more...
If you recall, find
has an -exec
option, which can be used to run a command on each of the files that match the search criteria. We can...