Linux – Fixing sed: -e Expression Unknown Option to `s’

bashlinuxshell

I know this has been asked before, but im struggling to determine the root cause of the error with my script. Ive gone through the other questions and tried to convert this (switched the /\ for @) but it just doesn't work for me i still get the same error???

As soon as i added in the last 4(from the bottom) expressions i started getting errors,..

when i run this

clustername="'XXXCluster'"  
seed=xx.xxx.xxx.xx  
ip=xx.xxx.xxx.xx  
hint="/opt/cassandra/data/hints"  
data="/opt/cassandra/data/data"  
commitlog="/opt/cassandra/data/commitlog"  
cache="/opt/cassandra/data/saved_caches"  

sed -i -e "s/\(cluster_name:\).*/\1$clustername/" \  
-e "s/\(- seeds:\).*/\1$seed/" \  
-e "s/\(listen_address:\).*/\1$ip/" \  
-e "s/\(rpc_address:\).*/\1$ip/" \  
-e "s/\(broadcast_rpc_address:\).*/\1$ip/" \  
-e "s/\(hints_directory:\).*/\1$hint/" \  
-e "s/\(data_file_directory:\).*/\1$data/" \  
-e "s/\(commitlog_directory:\).*/\1$commitlog/" \  
-e "s/\(saved_caches_directory:\).*/\1$cache/" /opt/cassandra.yaml  

i get this
sed: -e expression #6, char 29: unknown option to `s'

but i cant see how to fix this, can someone help me please??

thanks in advance..

Best Answer

Use % instead of / in your sed.

sed -e 's%search_string%replace_with%'

I guess your problem line has slashes in it and sed will strugle with it.

Edit:

Since you are using variables for the replace string, your slashes in there matters.

My first answer was a bit missleading. Sorry for that.

Example:

We have a file nada.txt with content 'test: "/a/place/in/universe"'

$ cat nada.txt
test: "/a/place/in/universe"

A variable with a directory for the replacement

$ dir="/new/place/in/haven"
$ echo $dir
/new/place/in/haven

Let's try to fail

$ sed -e "s/\(test: \).*/\1$dir/" nada.txt
sed: -e expression #1, char 19: unknown option to `s'

Again but this time with replaced slashes with % ("s///" to "s%%%")

$ sed -e "s%\(test: \).*%\1$dir%" nada.txt
test: /new/place/in/haven

Or

$ sed -e 's%\(test: \).*%\1'$dir'%' nada.txt
test: /new/place/in/haven

See the single quotes, you need four to take out the variable. It looks like this 's% %'$dir'%'Because in a shell context single quotes will not resolve the variable:

$ echo 'Such a text and $dir'
Such a text and $dir

Where as double quotes do the job as expected.

$ echo "Such a text and $dir"
Such a text and /new/place/in/haven 

Hope that helps