简体   繁体   中英

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.

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:

${string/substring/replacement}

 Replace first match of $substring with $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

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