SSH - Recursive find and replace
I'm rather new to bash and a few others, and I have looked online and found many solutions to somewhat do what I need, but I am looking for the optimal way.
Some people use sed
, others use find
.
I am trying to find and replace something within all files in a directory (recursively).
Any suggestions on how to do it or where to look?
EDIT
I am aware, now, thi开发者_高级运维s does not directly have to do with SSH, but it is where I was looking for answer and I feel others may also look in the same place.
find . -type f | xargs -d "\n" perl -pi -e 's/search/replace/g'
find . -type f
--> this finds all the files from the current directory recursively.
xargs -d "\n"
--> this will make the every line in the output of above command as the arguments to the below part.
perl -pi -e 's/search/replace/g'
---> this will take input from the above command and process each and every file to find the string and replace it.
"replace" is a command that comes with mysql. A bit strange for that command to come with mysql I agree. Most linux distros either already have mysql installed, or lets you install it through just a few clicks.
The syntax is like this: replace from1 to1 from2 to2 -- file1 file2 ...
from1 gets replaced by to1 and from2 gets replaced by to2. You can have any number of pairs. To only replace from1 to to1: replace from1 to1 -- file1 file2 ...
file1 file2 ... is a list of files to search-and-replace on. If you're in a directory that you wish to perform the search-and-replace on, recursively, you do: replace from1 to1 -- $(find -type f)
$() executes the command inside the parenthesis and inserts its printed results as arguments. Carriage returns are replaced with spaces.
So, let's say to with to replace all occurrences of the word "Mike" into the word "Joe", and you're in the directory you wish to start at, and consider all files recursively:
replace Mike Joe -- $(find -type f)
find can be combined with another program such as perl in a single command (no pipe). Basically find will execute perl for each matching file.
find . -type f -exec perl -pi -e 's/search/replace/g' {} \;
精彩评论