Reputation: 455
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.
Upvotes: 4
Views: 3060
Reputation: 289495
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
Upvotes: 6