1

I am using the below command on the local machine and it gives me the expected result:

sed -n 's/^fname\(.*\)".*/\1/p' file.txt

When I use the same command(only changed ' to ") to a same file present in the remote system, I do not get any output.

ssh remote-system "sed -n "s/^fname\(.*\)".*/\1/p" file.txt"

Please help me to get this corrected. Thanks for your help.

Sanjivi
  • 75
  • 1
  • 9
  • Use single quotes or escapes. ' and " are not interchangeable. – pvg May 31 '17 at 19:41
  • I did use single quotes, but I got the below error: `sed: -e expression #1, char 16: invalid reference \1 on `s' command's RHS` – Sanjivi May 31 '17 at 19:43
  • Remember that ssh invokes a shell command on the remote side, so you need two levels of quoting: one for the local shell and one for the remote shell. It's usually easier to put single quotes around the remote command and arrange to write that command with no single quote. – Harini Jun 01 '17 at 02:10

1 Answers1

0

" and ' are different things in bash, and they are not interchangeable (they're not interchangeable in many languages, however the differences are more subtle) The single quote means 'pretend everything inside here is a string'. The only thing that will be interpreted is the next single quote.

The double quote allows bash to interpret stuff inside

For example,

echo "$TERM"

and

echo '$TERM'

return different things.

(Untested) you should be able to use single quotes and escape the internal single quotes :

ssh remote-system 'sed -n \'s/^fname(.)"./\1/p\' file.txt'

Looks like you can send a single quote with the sequence '"'"' (from this question)

so :

ssh remote-machine 'sed -n '"'"'s/^fname\(.*\)".*/\1/p'"'"' file.txt'

This runs on my machine if I ssh into localhost, there's no output because file.txt is empty, but it's a proof-of-concept.

Or - can you do the ssh session interactively/with a heredoc?

ssh remote-system
[sed command]
exit

or (again untested, look up heredocs for more info)

ssh remote-system <<-EOF
    [sed command]
EOF
Brydon Gibson
  • 1,179
  • 3
  • 11
  • 22
  • `ssh remote-system 'sed -n \'s/^fname\(.*\)".*/\1/p\' file.txt'` didnt work. The statement is not completing as well. Also, I will have to use the statement within a script – Sanjivi May 31 '17 at 20:02
  • I've edited with an update, the escaped quotes were a guess, I've never actually used them. – Brydon Gibson Jun 01 '17 at 13:12