3

I'm using bash. I have a CSV file with two columns of data that looks roughly like this

 num_logins,day
 253,2016-07-01
 127,2016-07-02

I want to swap the first and second columns (making the date column the first one). So I tried this

awk ' { t = $1; $1 = $2; $2 = t; print; } ' /tmp/2016_logins.csv 

However, the results are outputting the same . What am I missing in my awk statement above to get things to switch properly?

4

Here you go :

  awk ' FS="," { print $2 "," $1 } ' sampleData.csv 
6

Because default delimiter is space/tab. Not comma. Taking your original code, and adding a -F, solves it.

$ awk -F, ' { t = $1; $1 = $2; $2 = t; print; } ' /tmp/2016_logins.csv
day num_logins
2016-07-01  253
2016-07-02  127
$

Stripping it down to {$0=$2" "$1}1 gets same result.

$ awk -F, '{$0=$2" "$1}1' /tmp/2016_logins.csv
day num_logins
2016-07-01  253
2016-07-02  127
$
  • 3
    Set OFS to get commas in the output too. – Kusalananda Aug 6 '18 at 19:30
  • And this one would leave columns 3+ alone, rather than throwing them away. – Monty Harder Aug 6 '18 at 22:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.