
我有一大堆文件,需要替換其中的完整 URL 方案。有些檔名包含空格。經過大量搜索、實際和錯誤後,這是我最接近的:
find /somedir -type f -print0 -exec sed -i'' -e 's#http\\:\\/\\/domain.com#https\\:\\/\\/www.domain.com#g' {} +
產生的檔案已http:
刪除該方案,留下//
- 即“//www.domain.com”
此外,還會建立一個新文件,並將其附加-e
到文件名稱中。 - 即some file.php-e
這顯然是不需要的。
雖然這肯定足夠了(刪除文件後*-e
,我內心的強迫症真的想知道如何正確地執行此操作。注意:我在 Mac 上本地工作,但也會在 Linux 上執行此操作。
任何想法都將不勝感激!
答案1
解決方案1:一種方法是find
使用xargs
:
find /dir -type f -print0 | xargs -0 sed -i 's#http://domain.com#https://www.domain.com#g'
解決方案2:另一種方法是使用find
with -exec
,與您的問題非常相似:
find /dir -type f -exec sed -i 's#http://domain.com#https://www.domain.com#g' {} +
兩種解決方案都將以sed
多個檔案作為參數進行呼叫。所以sed
不是為每個文件調用一次,而是為每組文件調用一次。
解決方案3: 除了 之外sed
,您還可以使用perl
search-replace-job:
perl -i -pe 's#http://domain.com#https://www.domain.com#g' file
find
與/命令結合xargs
:
find /dir -type f -print0 | xargs -0 perl -i -pe 's#http://domain.com#https://www.domain.com#g'