简体   繁体   English

bash:替换。 与\\。 在变量中

[英]bash: replace . with \. in a variable

Below is my questions 以下是我的问题

RELEASE_BRANCH=5.2.2

echo $RELEASE_BRANCH | sed 's/\./\\./g'
5\.2\.2

RELEASE=`echo $RELEASE_BRANCH|sed 's/\./\\./g'`

echo $RELEASE
5.2.2

What I am expecting 我期待什么

echo $RELEASE
5\.2\.2

Any ideas? 有任何想法吗?

Use of back-ticks is deprecated. 不建议使用引号。 You should use command substitution instead. 您应该改为使用命令替换

#!/bin/bash

RELEASE_BRANCH=5.2.2
RELEASE=$(echo $RELEASE_BRANCH|sed 's/\./\\./g')

echo "$RELEASE"

Note: Please read the Important differences (bullet 1) from the link for more details. 注意:请阅读从重要差异(子弹1) 联系了解更多详情。

If I understand you, then this should give you your expected result - 如果我了解您,那么您应该会得到预期的结果-

$ RELEASE=$(echo $RELEASE_BRANCH|sed 's/\./\\./g')
$ echo $RELEASE
5\.2\.2

由于您使用的是反引号,因此您需要多花一次转义反斜杠:

RELEASE=`echo $RELEASE_BRANCH|sed 's/\\./\\\\./g'`

You also use this method, 您也使用此方法,

$RELEASE=`echo $RELEASE_BRANCH|sed -r 's/\./\\\&/g'`
$echo $RELEASE
 5\.2\.2

We seldom think about the powerful string-manipulation functions made available by bash , and in this case the following works very well: 我们很少考虑bash提供的强大的字符串操作功能,在这种情况下,以下功能非常有效:

${string/substring/replacement} $ {string / substring / replacement}

 Replace first match of $substring with $replacement. 

${string//substring/replacement} $ {string // substring / replacement}

 Replace all matches of $substring with $replacement. 

So here we are going to use the second version, to have a neat one-liner: 因此,在这里我们将使用第二个版本,以实现简洁的单线:

$ RELEASE_BRANCH=5.2.2
$ echo ${RELEASE_BRANCH//./\\.}
5\.2\.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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