I am trying to replace a string in a file that which is on a remote machine. Firstly, I have to get the line number using grep command and then by using that line number should replace the string that which is there in that line.

My code looks like: my script file sc.sh.

# path of script.sh on remote machine

#file-[0-9]\.[0-9]\.[0-9]\.txt using for file-1.0.5.txt

sshpass -p 'pswd' ssh user@remote-01 "bash -s" <<EOF
n=$(grep -wn "/tmp/xyz/file-[0-9]\.[0-9]\.[0-9]\.txt\" $file_path | cut -d : -f 1)

sed -i '{$n}s/old_string/new_string/}' $file_path;

the commands in EOF block are working on my host machine but these commands are not working on remote machine, while using ssh. Can someone help me ? TIA.


sshpass -p 'pswd' ssh user@remote-01 "bash -s" <<EOF
sed -i -e '\|/tmp/xyz/file-[0-9]\.[0-9]\.[0-9]\.txt|s/old_string/new_string/' "$file_path"


  • Assuming your /home/user/script.sh file is visible on the remote m/c, then there's no need to first look for line numbers where the s/// commands need to happen. You need to realize the sed allows for /regex/s/// as well to select the line numbers where the subs will be made.
| improve this answer | |
  • file_path="/home/user/script.sh" is the file location on remote machine. – Ejjagiri Venkatesh Apr 25 '17 at 5:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.