我如何查找并替换每次出现的:
subdomainA.example.com
具有
subdomainB.example.com
递归地在/home/www/目录树下的每个文本文件中?
我如何查找并替换每次出现的:
subdomainA.example.com
具有
subdomainB.example.com
递归地在/home/www/目录树下的每个文本文件中?
当前回答
使用grep和sed的组合
for pp in $(grep -Rl looking_for_string)
do
sed -i 's/looking_for_string/something_other/g' "${pp}"
done
其他回答
cd /home/www && find . -type f -print0 |
xargs -0 perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g'
我只是需要这一点,并对现有示例的速度感到不满意。所以我想出了自己的办法:
cd /var/www && ack-grep -l --print0 subdomainA.example.com | xargs -0 perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g'
Ack-grep在查找相关文件方面非常有效。这个命令轻而易举地替换了约145000个文件,而其他命令耗时太长,我无法等到它们完成。
根据这篇博文:
find . -type f | xargs perl -pi -e 's/oldtext/newtext/g;'
试试看:
sed -i 's/subdomainA/subdomainB/g' `grep -ril 'subdomainA' *`
对于IBMi上的Qshell(qsh),不是OP标记的bash。
qsh命令的限制:
find没有-print0选项xargs没有-0选项sed没有-i选项
因此,qsh中的解决方案:
PATH='your/path/here'
SEARCH=\'subdomainA.example.com\'
REPLACE=\'subdomainB.example.com\'
for file in $( find ${PATH} -P -type f ); do
TEMP_FILE=${file}.${RANDOM}.temp_file
if [ ! -e ${TEMP_FILE} ]; then
touch -C 819 ${TEMP_FILE}
sed -e 's/'$SEARCH'/'$REPLACE'/g' \
< ${file} > ${TEMP_FILE}
mv ${TEMP_FILE} ${file}
fi
done
注意事项:
解决方案不包括错误处理不是OP标记的Bash