简体   繁体   中英

Linux : Replace key-value pair, value contains file path

I have a config file that looks like this

client {
keyTab="/home/path"
}

I want to change the keyTab key value based on current directory. My script goes like this

#!/bin/bash

DIR="$( cd "$(dirname "${BASH_SOURCE[0]}" )" && pwd )"
sed -c -i "s/\(keyTab\s*=\s*\).*$/\1NEWPATH/" file.cfg

When i run this script the "/home/path" is replaced by NEWPATH . However when i change the sed to

sed -c -i "s#^\(keyTab\s*=\s*\).*$#\1NEW/PATH#' file.cfg

then nothing happens. I am expecting the value to change to NEW/PATH . Eventually my aim is to replace the value in config with contents of DIR variable.

Please s(h)ed some light on how to make sed work in this case.

===========================================================

Update : After taking major hints from the answers provided below i was able to get it working. Following line does exactly what i want..

sed -i 's|\(keyTab\s*=\).*|\1"'"$DIR"'"|' file.conf

sed approach:

DIR="$( cd "$(dirname "${BASH_SOURCE[0]}" )" && pwd )"
sed -i 's#^\(keyTab\s*=\).*#\1"'"$DIR"'"#' file.cfg

以下是我的sed的工作原理:
sed -i 's/^\\(keyTab=\\).*/\\1NEW\\/PATH/' test.conf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM