shell sed命令使用心得

在使用sed過程中出錯:

sed -i "s/$sub/$rep/g" tmp

當變量sub或者變量rep中有字符'/'時,執行sed命令會出錯。

在網上查了很多資料,查出來原因:變量替換後有'/',跟sed 替換的'/'衝突 


解決方法:將變量中的字符'/'替換爲'\/'。

下面代碼的功能:替換文件tmp中dir的目錄'/a/b/c'爲'/1/2/3'


#!/bin/bash

echo 'dir=/a/b/c/d' > tmp
fname=tmp

if [ -f $fname ]
then
    lpath=`sed -n /dir/p "$fname"`
fi

if [ ${#lpath} -gt 0 ]  
then
    tmp=${lpath#*/}
    tmp2=/${tmp%/*}
    tmp3=${tmp2//\//\\/}
fi

new_dir='\/1\/2\/3'

sed -i "s/$tmp3/$new_dir/g" $fname
cat $fname


註釋:

${#lpath}: 獲取字符串lpath的長度

${lpath#*/}:從字符串lpath的開頭開始,刪除最短匹配字符'/'的子串

${tmp%/*}: 從字符串tmp的結尾開始,刪除最短匹配字符'/'的子串

${tmp2//\//\\/}: 將字符串tmp2中字符'/'替換爲'\/'


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章