Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

用 sed 批次替換檔案中的字串(含 Shell 函式封裝)

在 Linux 中要替換文字檔裡的某個字串,sed 是最順手的工具。

基本用法

把 test.txt 中所有的 desc 換成 helloworld:

sed "s#desc#helloworld#g" test.txt > test.txt.temp
mv test.txt.temp test.txt

這裡有兩個細節值得說明:分隔符用 # 而非傳統的 /,是為了避免字串本身含斜線時必須處處跳脫;而 sed 預設不會改寫原檔,因此必須導向暫存檔再覆蓋回去。g 代表 global,不加的話每行只會替換第一個符合項。

封裝成函式

function replacePara()
{
    old=$1
    new=$2
    file=$3
    sed "s#$old#$new#g" $file > $file.temp
    mv $file.temp $file
}

呼叫方式:

replacePara desc helloworld test.txt

即可把 test.txt 中的 desc 全部替換為 helloworld。

若你的 sed 是 GNU 版本,其實有更簡潔的原地編輯寫法,不必自己搬暫存檔:

sed -i "s#desc#helloworld#g" test.txt
sed -i.bak "s#desc#helloworld#g" test.txt   # 額外保留 .bak 備份

另外提醒:若 old 或 new 中可能出現 &(代表「整個符合字串」)或反斜線,仍需要跳脫處理。

Copyright © Linux教程網 All Rights Reserved