I want to know if there is a way to easier way to swap the first two words of every line.

Let say my text file consist of these three lines:

 Mary Joe
 William Edward
 Shawn Liam

Ultimately I want this:

 Joe Mary 
 Edward William
 Liam Shawn

I know this can be done by sed command by doing this:

sed -e "s/\([^ ]*\) *\([^ ]*\)/\2 \1 /g" file

But thats to much to remember.

Is there an easier way to do this.

This is bash btw.

  • 1
    If your version of sed supports extended regular expression syntax, you can simplify that somewhat e.g. sed -E 's/(\S+)\s+(\S+)/\2 \1/'. Note that the g modifier is not required if you want to swap only the first two columns of each line. – steeldriver Feb 25 '16 at 12:41

With two word lines, this might be easier:

awk '{print $2,$1}' file

If you need to swap the first two words of a file with or without two words per line:

awk 'NF >= 2{t=$2;$2=$1;$1=t};{print}' file

Note that this will collapse multiple spaces into one.

  • that first command is way easier, thanks! – shawn edward Feb 25 '16 at 4:07

If your words are space delimited, then awk can be easier:

awk 'NF > 1 {a = $1; $1 = $2; $2 = a};1' <file

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.