0

I am trying to use SED command with a variable that contains several / and i got the following error :

sed: -e expression 1, char 16: unknown option to s

this is my code and this is inside a script:

thispath=$(readlink -f $0)
sudo sed -i '13s/^/'"$thispath"'/g' /etc/rc.local

and the variable contains for example: /home/user/script.sh i do not know very well the use of sed can somebody help me

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
shaveax
  • 458
  • 6
  • 16

1 Answers1

2

The s command is sed allows you to use any character to delimit the regex and replacement parts. "/" is often a poor choice given how often you come across it in UNIX paths:

Try:

sudo sed -i '13s:^:'"$thispath"':g' /etc/rc.local

It is dangerous to do this directly on rc.local. So make a copy first.

Beano
  • 7,551
  • 3
  • 24
  • 27
sureshvv
  • 4,234
  • 1
  • 26
  • 32
  • 1
    just be aware that it's just a band-aid and will fail when the text contains `:` or `&` or `\1` or some other char/string that sed interprets as something other than a literal char. – Ed Morton Sep 20 '15 at 17:32
  • If you're going to suggest making a backup, you may as well add a suffix to the `-i` switch e.g. `-i.bak` so that one is created by the code in your answer. – Tom Fenech Sep 20 '15 at 17:35
  • @EdMorton I guess `awk -v str="$var" 'NR==13{printf "%s", str}1' file` could fix the delimiter problem, but it's a bit more complex and doesn't handle inplace editing without a recent gawk. – user000001 Sep 20 '15 at 17:35
  • Yup, as often is the case it's a choice between brief or robust. To use sed for this see http://stackoverflow.com/q/29613304/1745001. – Ed Morton Sep 20 '15 at 17:43