我們知道一般的sed文本替換命令格式如下:
sed -e "s/origin/new/g" input.txt
但當我們要替換的東西或替換後的東西不再像origin或new這樣,而是一個路徑時怎麼辦呢?答案是轉義!!
例如我有以下input.txt的文本
1. set path VARPATH running workspace. 2. runing this program我想把裡面的VARPATH替換為/var/tmp/cloud,用shell腳本實現如下:
!/bin/sh
###########################################################
# sedpath.sh
# this script is used to deal with sed replace with path
###########################################################
VARPATH="/var/tmp/cloud"
VARPATHSED=$(echo ${VARPATH} |sed -e 's/\//\\\//g' )
echo "origin content:"
echo "-----------------"
cat input.txt
echo "-----------------"
echo "VARPATH=${VARPATH}"
echo "VARPATHSED=${VARPATHSED}"
cat input.txt |sed -e "s/VARPATH/${VARPATHSED}/g" > output.txt
echo "the result content:"
echo "-----------------"
cat output.txt
echo "-----------------"
運行結果如下: