0

I am new in bash script I have variable

TEST="https://myhost/mydomain/

I need to change it to

 TEST="https:\/\/myhost\/mydomain\/

How I can do it ?

user1365697
  • 5,819
  • 15
  • 60
  • 96
  • 3
    *Why* do you need to do that? It's an important question because if you expect those backslashes to be treated as syntax rather than literal data on expansion, you're in for a surprise. – Charles Duffy Feb 06 '19 at 13:05

1 Answers1

1

using variable expansion

TEST="https://myhost/mydomain/"

TEST=${TEST//\//\\/}

Bash manual parameter expansion

  • first // after TEST means replace all occurences
  • the next / must be escaped because / is the delimiter between pattern and replacement string
  • then the backslash must be escaped because it's an escape character

${parameter/pattern/string}

The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. The match is performed according to the rules described below (see Pattern Matching). If pattern begins with ‘/’, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with ‘#’, it must match at the beginning of the expanded value of parameter. If pattern begins with ‘%’, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If the nocasematch shell option (see the description of shopt in The Shopt Builtin) is enabled, the match is performed without regard to the case of alphabetic characters. If parameter is ‘@’ or ‘’, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.

Community
  • 1
  • 1
Nahuel Fouilleul
  • 18,726
  • 2
  • 31
  • 36