-5

I need to SFTP a file to a server. The password has a dollar sign $ and I need to escape it.

I tried with Perl and sed commands I am able to replace but the string following $ is not getting added.

Example:

echo "Np4$g" | perl -pe 's/$/\\\\\$/g'

output

Np4\\$

It supposed to be Np4\\$g, but g is not getting appended.

Code:

/usr/bin/expect <<EOF
set timeout -1
spawn sftp -C -oPort=$port $sftp_username@$host_name
expect "password:"
send "$password\r"
expect "sftp>"
cd $remote_dir
send "mput *.txt\r"
expect "sftp>"
send
Borodin
  • 126,100
  • 9
  • 70
  • 144
mithun
  • 1
  • /usr/bin/expect <" cd $remote_dir send "mput *.txt\r" expect "sftp>" send "quit\r" EOF – mithun May 07 '17 at 16:02
  • 1
    See: [Difference between single and double quotes in bash](http://stackoverflow.com/q/6697753/3776858) – Cyrus May 07 '17 at 16:08

2 Answers2

2

Your command

echo "Np4$g" | perl -pe 's/$/\\\\\$/g'

is failing for two reasons

  • In "Np4$g", the shell is interpolating the variable g into the double-quoted string. It probably isn't defined so it is replaced with nothing, and you are passing just Np4 to perl. You need to use single quotes to prevent the interpolation

  • In the Perl substitution s/$/\\\\\$/g the $ in the pattern matches the end of the string, not a literal dollar. That means Np4 is changed to Np4\\$. You need to escape the dollar sign in the pattern to get it to match a literal $

This will work correctly

echo 'Np4$g' | perl -pe 's/\$/\\\$/g'

output

Np4\$g
ikegami
  • 367,544
  • 15
  • 269
  • 518
Borodin
  • 126,100
  • 9
  • 70
  • 144
1

I suggest to not escape and replace

"Np4$g"

by

'Np4$g'
Cyrus
  • 84,225
  • 14
  • 89
  • 153