sed command returning "sed: bad option in substitution expression"

6,300

Solution 1

The problem has to do with the fact that the sed delimiter is / and it collides with the text in $key. To solve it, use another delimiter. For example, #:

$ key="1/2/3/4"
$ echo 1/2/3/4 | sed "s#$key#\"$key\"#" 
"1/2/3/4"

Or

$ echo "hello this is 1/2/3/4 yeah" | sed "s#$key#\"$key\"#"
hello this is "1/2/3/4" yeah

Interesting reading: What delimiters can you use in sed?. Spoiler: almost everything!

Solution 2

Perl to the rescue:

perl -pe 's/\$([[:alnum:]]+)/$ENV{$1}/'

Explanation:

  • \$ matches the dollar sign.
  • [[:alnum:]] matches digits, letters and underscore, i.e. valid identifier characters. The + means there must be at least one such character.
  • (...) introduces a capture group.
  • $ENV{$1} retrieves the value from the %ENV hash which contains the environment variables. Perl doesn't expand variables like shell, so the variable can contain / (or whatever else) without harm.

Example:

$ echo '$key' | key=1/2/3/4 perl -pe 's/\$([[:alnum:]]*)/$ENV{$1}/'
1/2/3/4
Share:
6,300

Related videos on Youtube

Vishnu Nair
Author by

Vishnu Nair

Updated on September 18, 2022

Comments

  • Vishnu Nair
    Vishnu Nair over 1 year

    For example:- I have a file named file.txt

    $ cat file.txt
    $key
    

    I have a environment variable, for eg: $key in a text file

    and lets say $key = 1234, so I can replace the value with the below command

    sed -i 's/$key/'"$key"'/' file.txt 
    

    and it becomes

    $ cat file.txt
    1234
    

    My problem is that if the value for

    $key = 1/2/3/4
    

    I'm not able to run the below command

    sed -i 's/$key/'"$key"'/' file.txt  
    

    It will give an error

    sed: bad option in substitution expression
    

    Because of the slash it's breaking. I can solve it by giving the value directly but I don't want to use it in that way.

    sed -i 's/$key/1\/2\/3\/4/' file.txt 
    
  • choroba
    choroba over 8 years
    The problem is when you don't know what characters the variable will contain.