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
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
$2 won't be replaced with its value inside single quotes. Should work with double quotes.
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?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.
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
fgrep -v "$2" authorized_keys ...!fgrep -v "$2" /root/.ssh/authorized_keys > /root/.ssh/authorized_keys and it just clears out the entire authorized_keys file.