我如何查找并替换每次出现的:
subdomainA.example.com
具有
subdomainB.example.com
递归地在/home/www/目录树下的每个文本文件中?
我如何查找并替换每次出现的:
subdomainA.example.com
具有
subdomainB.example.com
递归地在/home/www/目录树下的每个文本文件中?
当前回答
我很惊讶我没有看到使用文件globbing的简单答案,我只使用**/package.json扫描/更新package.json文件
这是zsh下macos特有的
cd /home/www
sed -i '' -e 's/subdomainA.example.com/subdomainA.example.com/g' **/*
其他回答
#!/usr/local/bin/bash -x
find * /home/www -type f | while read files
do
sedtest=$(sed -n '/^/,/$/p' "${files}" | sed -n '/subdomainA/p')
if [ "${sedtest}" ]
then
sed s'/subdomainA/subdomainB/'g "${files}" > "${files}".tmp
mv "${files}".tmp "${files}"
fi
done
将当前目录和子目录(不包括.git/)中所有.c和.h文件的所有匹配string_1的内容替换为string_2。
这适用于Mac:
find . -type f -path "*.git*" -prune -o -name '*\.[ch]' -exec \
sed -i '' -e 's/'$1'/'$2'/g' {} +
这应该可以在Linux上运行(尚未测试):
find . -type f -path "*.git*" -prune -o -name '*\.[ch]' -exec \
sed -i 's/string_1/string_2/g' {} +
您可以使用awk解决如下问题,
for file in `find /home/www -type f`
do
awk '{gsub(/subdomainA.example.com/,"subdomainB.example.com"); print $0;}' $file > ./tempFile && mv ./tempFile $file;
done
希望这对你有帮助!!!
find /home/www/ -type f -exec perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g' {} +
find/home/www/-type f将列出/home/ww/(及其子目录)中的所有文件。“-exec”标志告诉find对找到的每个文件运行以下命令。
perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g' {} +
是在文件上运行的命令(一次运行多个)。{}被文件名替换。告诉find为多个文件名构建一个命令。
根据查找手册页:“命令行的构建方式与xargs构建其命令行。"
因此,不使用xargs-0或-print0就可以实现目标(并处理包含空格的文件名)。
试试看:
sed -i 's/subdomainA/subdomainB/g' `grep -ril 'subdomainA' *`