How to change all occurrences of a word in all fil

2019-01-22 03:16发布

问题:

I was in the process of creating a User class where one of the methods was get_privileges();.

After hours of slamming my head into the keyboard, I finally discovered that the previous coder who I inherited this particular database spelled the word "privileges" as "privelages" in the MySQL database, and thus also everywhere in the hundreds of files that access these "privelages" it is spelled that way.

Is there a way in Linux (Ubuntu Server) that I can go through every place in the /var/www folder and replace "privelages" with "privileges", so that I don't have to deal with this typo and code around it?

回答1:

A variation that takes into account subdirectories (untested):

find /var/www -type f -exec sed -i 's/privelages/privileges/g' {} \;

This will find all files (not directories, specified by -type f) under /var/www, and perform a sed command to replace "privelages" with "privileges" on each file it finds.



回答2:

Check this out: http://www.cyberciti.biz/faq/unix-linux-replace-string-words-in-many-files/

cd /var/www
sed -i 's/privelages/privileges/g' *


回答3:

I generally use this short script, which will rename a string in all files and all directory names and filenames. To use it, you can copy the text below into a file called replace_string, run sudo chmod u+x replace_string and then move it into your sudo mv replace_string /usr/local/bin folder to be able to execute it in any directory.

NOTE: this only works on linux (tested on ubuntu), and fails on MacOS. Also be careful with this because it can mess up things like git files. I haven't tested it on binaries either.

#!/usr/bin/env bash

# This will replace all instances of a string in folder names, filenames,
# and within files.  Sometimes you have to run it twice, if directory names change.


# Example usage:
# replace_string apple banana

echo $1
echo $2

find ./ -type f -exec sed -i -e "s/$1/$2/g" {} \;  # rename within files
find ./ -type d -exec rename "s/$1/$2/g" {} \;    # rename directories
find ./ -type f -exec rename "s/$1/$2/g" {} \;  # rename files