dave
dave

Reputation: 12806

Awk is inserting whitespace

I am trying to swap two columns in a csv file and I'm using this:

#!/usr/bin/awk -f

BEGIN {FS="$\t"}
{temp=$1; $1=$2; $2=temp}{print$0}

Which works great, except it's adding an extra whitespace at the beginning of the line. How can I prevent this?

My input file looks like this

1\t2
3\t4

What I get looks like this:

 2\t1
 3\t4

Upvotes: 2

Views: 84

Answers (2)

Kent
Kent

Reputation: 195229

why you have the dollar in your FS?

I don't think your current FS even work. ... remove the $, and it should be ok.

for the reason of the leading empty:

with your current FS, $\t means a tab after the end of line. which will match nothing. that is, after processed by awk, each line of your file has only one field. There is only $0 and $1 there is no $2 at all. so $2 is empty.

you did the swap, actually you just add an empty field to your original line. And because you reset a field ($1 and $2), when you print $0, awk will apply OFS on the line, in your case, OFS is default, a space. so, awk will print:

$2<space>$1

keep in mind, $2 is empty and $1 is actually your $0.

Upvotes: 3

Karoly Horvath
Karoly Horvath

Reputation: 96306

It's caused by setting the FS to the wrong value.

You want FS="\t".

Upvotes: 2

Related Questions