Find and Replace: Difference between revisions
(4 intermediate revisions by the same user not shown) | |||
Line 13: | Line 13: | ||
</code> | </code> | ||
== | === Find and Remove === | ||
The find comand is also useful if you want to remove specific files from a directory. Such as only files ending in .png within an images directory | |||
<code> | <code> | ||
$ | $ find /path/to/directory -type f -name '*.png' -exec rm -ri {} \; | ||
</code> | </code> | ||
'''Note:''' <code>rm -ri </code> for recursive/interactive deletion to be used in cases where you're unsure about deleting all .png files. <code>rm -rf</code> if you want to forcefully delete all files. | |||
== Alternative methods == | |||
=== sed === | |||
<code>$ cd /path/to/your/folder </code><br> | |||
<code>$ sed -i 's/foo/bar/g' *</code> | |||
All occurrences of the string "foo" will be replaced with the string "bar". | All occurrences of the string "foo" will be replaced with the string "bar". | ||
== Perl == | === Perl === | ||
<code>perl -pi -w -e 's/search/replace/g;' *.php </code> | <code>perl -pi -w -e 's/search/replace/g;' *.php </code> |
Latest revision as of 12:56, 2 August 2017
Find and Replace
With SSH access, you can replace a string of text within multiple files within a single command. For example, to update every instance of your phone number in all of your files, you would do the following:
$ find ./ -type f -exec sed -i 's/987-654-3210/555-789-0210/g' {} \;
For insensitive search and replace of the string:
$ find ./ -type f -exec sed -i 's/string1/string2/gI' {} \;
Find and Remove
The find comand is also useful if you want to remove specific files from a directory. Such as only files ending in .png within an images directory
$ find /path/to/directory -type f -name '*.png' -exec rm -ri {} \;
Note: rm -ri
for recursive/interactive deletion to be used in cases where you're unsure about deleting all .png files. rm -rf
if you want to forcefully delete all files.
Alternative methods
sed
$ cd /path/to/your/folder
$ sed -i 's/foo/bar/g' *
All occurrences of the string "foo" will be replaced with the string "bar".
Perl
perl -pi -w -e 's/search/replace/g;' *.php
-e means execute the following line of code. -i means edit in-place -w write warnings -p loop