0

I am trying to remove a given line $2 from the file /root/.ssh/authorized_keys using sed. Here is the command I am running, unfortunately, its not deleting the line. Any idea what I'm doing wrong?

 sed -i '/$2/d' /root/.ssh/authorized_keys
1
  • Are you seeing an error message? Do you have write access to the file? Commented Sep 8, 2011 at 23:56

3 Answers 3

2

$2 won't be replaced with its value inside single quotes. Should work with double quotes.

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

3 Comments

sed -i "/$2/d" /root/.ssh/authorized_keys
Getting an error from sed. sed: -e expression #1, char 41: unknown command: 3'' Probably because the public key, has special sed characters in it. Is there a way to quote it?
Use a non-base64 valid character as sed's separator, something like this should work: sed -i "\,$2,d"
1

Posting a non-sed answer as suggested by Glenn Jackman. The basic "right answer" was already posted by Tom Zych; note also the comment by holygeek.

mv authorized_keys authorized_keys~
fgrep -v "$2" authorized_keys~ >authorized_keys

You could probably get by without the temporary file but I'm not at my computer so I'm playing it safe for now.

Comments

0

You can also use the shell

while read -r line
do
   case "$line" in 
     *"$2"* ) continue;;
     * ) echo "$line" ;;
   esac
done < /root/.ssh/authorized_keys > tempfile
mv tempfile /root/.ssh/authorized_keys

5 Comments

More like fgrep -v "$2" authorized_keys ...!
To the one who downvote, make sure you know why you downvote.
@tripleee, you might want to put that comment as an answer. It's the best answer I see here.
I tried fgrep -v "$2" /root/.ssh/authorized_keys > /root/.ssh/authorized_keys and it just clears out the entire authorized_keys file.
Yeah, you cannot redirect into the file you want to read from, you need a temporary file or some other workaround.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.