Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape dots in domains names using sed in Bash

Tags:

bash

escaping

sed

I am trying to keep the return of a sed substitution in a variable:

  • D=domain.com
    echo $D | sed 's/\./\\./g'
    

    Correctly returns: domain\.com

  • D1=`echo $D | sed 's/\./\\./g'`
    echo $D1
    

    Returns: domain.com

What am I doing wrong?

like image 805
Roger Avatar asked Aug 15 '11 00:08

Roger


2 Answers

D2=`echo $D | sed 's/\./\\\\./g'`
echo $D2

Think of shells rescanning the line each time it is executed. Thus echo $D1, which has the escapes in it, have the escapes applied to the value as the line is parsed, before echo sees it. The solution is yet more escapes.

Getting the escapes correct on nested shell statements can make you live in interesting times.

like image 116
Gilbert Avatar answered Sep 24 '22 12:09

Gilbert


The backtick operator replaces the escaped backslash by a backslash. You need to escape twice:

D1=`echo $D | sed 's/\./\\\\./g'`

You may also escape the first backslash if you like.

like image 40
Kerrek SB Avatar answered Sep 22 '22 12:09

Kerrek SB