Pregunta

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?

¿Fue útil?

Solución

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'

Otros consejos

Inside vi you can do this command:

:%!awk '{c3=$3; $3=$2; $2=c3} 1'
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top