[英]How to change all occurrences of a word in all files in a directory
我正在创建一个User
类,其中一个方法是get_privileges();
.
之后砰我的头到键盘的时间,我终于发现,我是谁继承了这个特定的数据库先前编码的数百个文件的拼写单词“特权”,如MySQL数据库“privelages”,因而也处处访问这些“ privelages ”是这样拼写的。
在 Linux ( Ubuntu Server ) 中是否有一种方法可以遍历/var/www
文件夹中的每个位置并将“ privelages ”替换为“ privileges ”,这样我就不必处理这个错字和围绕它的代码?
考虑子目录的变体(未经测试):
find /var/www -type f -exec sed -i 's/privelages/privileges/g' {} \;
这将find
/var/www
下的所有文件(不是目录,由-type f
指定),并执行sed
命令以在它找到的每个文件上用“特权”替换“特权”。
看看这个: http : //www.cyberciti.biz/faq/unix-linux-replace-string-words-in-many-files/
cd /var/www
sed -i 's/privelages/privileges/g' *
我通常使用这个简短的脚本,它将重命名所有文件和所有目录名和文件名中的字符串。 要使用它,您可以将下面的文本复制到一个名为replace_string
的文件中,运行sudo chmod u+x replace_string
然后将其移动到您的sudo mv replace_string /usr/local/bin
文件夹中,以便能够在任何目录中执行它。
注意:这仅适用于 linux(在 ubuntu 上测试),在 MacOS 上失败。 还要小心这一点,因为它可能会弄乱 git 文件之类的东西。 我也没有在二进制文件上测试过它。
#!/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
对于Mac OS:
find . -type f -name '*.sql' -exec sed -i '' s/privelages/privileges/ {} +
如果Matwilso的脚本设计适用于Mac OS,那么上面的脚本将会是这样的
#!/bin/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 -name '*.sql' -exec sed -i '' s/${1}/${2}/ {} + # inside sql scripts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.