Search code examples
sshshscp

How to swap words position in a line using bash?


I have a command saved in string.

 toserver="scp -q -i ssh_key1.pem outfile ec2-user@ec2-18-205-233-131.compute-1.amazonaws.com:/home/ec2-user/outfile"

And, from the above I want to swap the file positions and create new variable. I mean, like below.

fromserver="scp -q -i ssh_key1.pem ec2-user@ec2-18-205-233-131.compute-1.amazonaws.com:/home/ec2-user/outfile outfile"

the outfile name won't change but the server address might change. Please suggest how to do this.


Solution

  • Using sed

    $ fromserver=$(printf '%s\n' "$toserver" | sed s'/\([^.]*\.[^ ]*\) \([^ ]*\) \(.*\)/\1 \3 \2/')
    $ echo "$fromserver"
    scp -q -i ssh_key1.pem ec2-user@ec2-18-205-233-131.compute-1.amazonaws.com:/home/ec2-user/outfile outfile