Delete line from remote file over ssh passing variable

I have a variable called $a1 which maps to something like "http://servername proxy1 count http" and a lots of entries in a file on remote server.
If I have the following in my .sh script:

sed -i "\%$a1%d" mylog.txt

the line is deleted from mylog.txt. Great.
I'm trying now to remvoe this from a remote server too:

echo $a1 | ssh -q -i ~/.ssh/mysshkey remoteserver "sed -i \"\%$a1%d\" mylog.txt"

This doesn't work. I also tried

 echo $a1 | ssh -q -i ~/.ssh/mysshkey remoteserver "sed -i '\%$a1%d\' mylog.txt"

Which also doesn't work.

I am missing something obvious?

Hi, you do not need the echo $a1 | part.

Try:

ssh -q -i ~/.ssh/mysshkey remoteserver "sed -i '\%$a1%d' mylog.txt"

There was a backslash before the last single quote.

Thanks for the spot.

It didn't quite work as you suggested, but when I added the echo back in, it worked. Many thanks:

echo $a1 | ssh -q -i ~/.ssh/mysshkey remoteserver "sed -i '\%$a1%d' mylog.txt"

The echo $a1 | ssh ... redirects stdin - but nothing reads from it.
You can just redirect stdin with </dev/null ssh ... or close stdin with ssh -n ... ; that should have the same effect and not confuse anybody.

2 Likes