Saturday, July 30, 2022

[SOLVED] How to swap words position in a line using bash?

Issue

I have a command saved in string.

 toserver="scp -q -i ssh_key1.pem outfile [email protected]:/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 [email protected]:/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 [email protected]:/home/ec2-user/outfile outfile


Answered By - HatLess
Answer Checked By - Marilyn (WPSolving Volunteer)