2016-09-27 211 views
0

我正在使用macOS Sierra,並且正在嘗試操作配置文件中的某個鍵的值。使用sed替換自定義字符串替代命令'/'壞標誌

爲了實現我使用(這對於簡單值正常工作):

sed -i .bak "/^$KEY/s/\(.[^=]*\)\([ \t]*=[ \t]*\)\(.[^=]*\)/\1\2$VALUE/" $CONFIG_FILE 

不幸的是,我的字符串$值與許多特殊字符相當複雜,給我的錯誤:

bad flag in substitute command: '/'

我的$值被聲明爲:

VALUE='<Request xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" ReturnPolicyIdList="false" CombinedDecision="false"> <Attributes Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource"> <Attribute IncludeInResult="false" AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id"> <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">test </AttributeValue> </Attribute> </Attributes> <Attributes Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action"> <Attribute IncludeInResult="false" AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id"> <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">testing something</AttributeValue> </Attribute> </Attributes> </Request>' 

因爲我有雙重曲otes是$ VALUE的價值的一部分,我不能使用雙引號而不是單引號時聲明它...任何想法解決這個問題?

回答

0

的問題是,$VALUE包含需要轉義,因爲它與分離的substiture命令

,因爲如果它的變化,你必須再次逃脫他們不方便衝突斜線。不過,這是一個解決方案。

另一個更簡單的解決方案是使用一個替代的分離對於s命令,它是不是在$VALUE字符串,如%例如字符(%具有較少的是在這樣的字符串的機會,否則也可使用|)。

sed -i .bak "/^$KEY/s%\(.[^=]*\)\([ \t]*=[ \t]*\)\(.[^=]*\)%\1\2$VALUE%" $CONFIG_FILE 

或用管:

sed -i .bak "/^$KEY/s|\(.[^=]*\)\([ \t]*=[ \t]*\)\(.[^=]*\)|\1\2$VALUE|" $CONFIG_FILE 
+0

工程就像一個魅力,反正我會建議使用不同的正則表達式,如:「S | \($ KEY [[:空間:]] * * = * \)。* | \ 1'$ VALUE'|「 – fcarvalho