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

當sed遇到路徑怎麼辦?

我們知道一般的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 "-----------------"

運行結果如下:

 \

Copyright © Linux教程網 All Rights Reserved