Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

CentOS 上用 find 正則表達式批次替換檔案內容

要在大量檔案中批次改字串,find 搭配 sed 是最省力的組合。以下這行指令會把 /opt 底下所有 properties、js、jsg、vm、html 檔案中的 baidu 換成 qq:

find /opt -regextype "posix-egrep" -regex ".*properties|.*js|.*jsg|.*vm|.*html" \
| while read L; do sed -i "s/www.baidu.com/www.qq.com/g" $L; done

幾個關鍵點:-regextype posix-egrep 讓 find 採用 ERE 語法,才能使用「或」的寫法;-regex 匹配的是完整路徑,所以前面要帶 .*;sed -i 表示直接改寫原檔。執行前建議先去掉 -i 或搭配備份,確認比對範圍無誤再實際寫入。

Copyright © Linux教程網 All Rights Reserved