0

In a bash script, I'm trying to replace a line which starts with a comment with new text. The sed fails telling me that the hash char is an Unknown option to s

sed -i -e "s/#a line/the new line with some $varname/g" "path/to/filename"

I've tried one backslash on the # to no avail. How do I use a hash with sed, and yes, I have to use double quotes to manage the variable use.

user3791372
  • 4,445
  • 6
  • 44
  • 78

1 Answers1

3

The problem has nothing to do with #. You get the error because the variable you are injecting into the sed script happen to contain / characters. If you know a character that will definitely not appear in the pattern or replacement, use that as separator for the s command instead. E.g. assuming | is safe:

sed "s|#a line|the new line with some $varname|" file > file.tmp &&
mv file.tmp file

Alternatively, the c command can be used to change the whole line:

sed "/#a line/c\\
the new line with some $varname" file > file.tmp &&
mv file.tmp file

Or better, find a way to do it without injecting data into code (E.g. ed, ex or awk)

geirha
  • 5,801
  • 1
  • 30
  • 35