Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap two columns with awk

Tags:

sed

awk

I try to swap two columns in a text file, the field separator is the pipe '|' sign.

I found and tried

awk ' { t = $1; $1 = $2; $2 = t; print; } ' input_file

it works when the field separator is the tab.

I also tried

awk -F\|  '{print $2 $1 }' input_file

but I do not manage to specify the '|' as output field separator.

like image 859
Fdv Avatar asked Sep 01 '25 20:09

Fdv


1 Answers

You need to define the OFS, Output Field Separator. You can do it with either of these ways:

awk 'BEGIN{FS=OFS="|"} {t=$1; $1=$2; $2=t; print} ' input_file

or

awk -v OFS="|" -v FS="|" ' {t=$1; $1=$2; $2=t; print} ' input_file

or (thanks Jaypal!)

awk '{t=$1; $1=$2; $2=t; print}' OFS="|" FS="|" input_file
like image 96
fedorqui 'SO stop harming' Avatar answered Sep 03 '25 23:09

fedorqui 'SO stop harming'