0

I have a file with data in the following format: cat file1

a b c d e
e f g h i
p q r s t

I want the output to be in the following format:

a c b d e
e g f h i
p r q s t 

What is the best way to do this swapping of two columns in vi or shell?

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Ajim Bagwan
  • 127
  • 3
  • 10
  • possible duplicate of [Swap two columns - awk, sed, python, perl](http://stackoverflow.com/questions/11967776/swap-two-columns-awk-sed-python-perl) – perreal Feb 07 '14 at 11:51
  • Sorry. I tried searching for it. But couldn't find it. I was searching for vi and unix shell. Perhaps you guys should add the tags for it in that answer and also include the vi version of the answer there. – Ajim Bagwan Feb 07 '14 at 11:59

2 Answers2

1

With awk for example:

$ awk '{a=$2; $2=$3; $3=a}1' file
a c b d e
e g f h i
p r q s t

You can make it more general with:

$ awk -v c1=FIRST_COL -v c2=SECOND_COL '{a=$c1; $c1=$c2; $c2=a}1' file

For example:

$ awk -v c1=2 -v c2=3 '{a=$c1; $c1=$c2; $c2=a}1' file
a b d c e
e f h g i
p q s r t

To use it from inside vi, use the following before the command:

:%!

So that the full command to execute is:

:%!awk '{a=$2; $2=$3; $3=a}1'
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 1
    And in vi, the following works: :%!awk '{a=$2; $2=$3; $3=a}1' Cool. Thanks. – Ajim Bagwan Feb 07 '14 at 11:54
  • To make it work in `vi` you just need to call it with `:%!`, [as Mark Plotnick said in your previous question](http://stackoverflow.com/questions/21624505/how-to-append-some-command-output-at-the-end-of-each-line-in-a-vi-file#comment32676522_21624605). – fedorqui Feb 07 '14 at 11:56
  • 1
    Yeah it works. Will accept the answer in next 4 minutes. – Ajim Bagwan Feb 07 '14 at 12:00
1

Inside vi you can do this command:

:%!awk '{c3=$3; $3=$2; $2=c3} 1'
anubhava
  • 761,203
  • 64
  • 569
  • 643