2

I am working on a script that among other things will delete a line from a file. The line to be deleted is stored in a variable, and constructed from a command line argument. Here's what I have so far:

#!/bin/sh
repo=$1
devscript=/usr/local/bin/svn-post-commit-update-$repo-dev
livescript=/usr/local/bin/svn-post-commit-update-$repo-live
sudoer="www-data    ALL=(root) NOPASSWD: $devscript, $livescript"
sed -i '//$sudoer/ d' /home/bdugan/t.txt

And I am getting the following error:

sed: -e expression #1, char 3: unknown command: `$'

I realize that at this point there is some simple syntax issue that I've messed up, but for the life of me I can't find it. Any ideas?

3 Answers 3

4

The key point is that you must use double quotes so the variable gets expanded. Otherwise, sed sees the dollar sign literally.

Also key is that your pattern contains slashes. You must use alternate delimiters:

sed -i "\|$sudoer|d" /home/bdugan/t.txt

Choose a delimiter that is unlikely to appear in the string.

Sign up to request clarification or add additional context in comments.

2 Comments

Start with a double quote and end with a single quote? Naaaah! And I belive escaping the pipe is not needed.
@Jens: The quote mismatch was a typo. You are right about the delimiters. I had thought the alternate address delimiter was a GNU extension.
2

Since your line contains / chars, it will mess up the /regex/ delimiters for sed. You might want to use awk and use string equality instead of a regex:

awk -v line="$sudoer" '$0 == line {next} {print}' ~/t.txt > ~/t.txt.new &&
mv ~/t.txt ~/t.txt.old &&
mv ~/t.txt.new ~/t.txt

Comments

1

try this

sed -e "'s@${sudoer}@@'" -e '/^$/d' -i /home/bdugan/t.txt

this will use @ as delimiter which is only possible for substition commands and afterwards delete empty lines.

EDIT: you shall not use / as a delimiter for filenames and path since it may break your sed regex

Update:

If you're using GNU sed you can reduce the command to

sed -e "'\@${sudoer}@d'" -i /home/bdugan/t.txt

6 Comments

be aware, that this command will delete every empty line in your file. If this is not an issue, it should work for you.
You could rewrite regexp as "@${sudoer}@d".
no you can't since sed doesn't allow alternative delimiter for any command except substitution commands (at least this is said by the documentation of sed, maybe there were changes lately). Would you mind testing it on your local machine and tell me if it's working ?
GNU sed allows alternate delimiters for address selectors so you can do "\@${sudoers}@d" (the first must be escaped). I would prefer "\|$sudoers|d" because it's less visually "heavy".
@DennisWilliamson, can you post your solution as an answer? It was what eventually worked for me.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.