8

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?

0

3 Answers 3

11

Here you go:

awk -F, '{ 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
$
2
  • 4
    Set OFS to get commas in the output too.
    – Kusalananda
    Commented Aug 6, 2018 at 19:30
  • And this one would leave columns 3+ alone, rather than throwing them away. Commented Aug 6, 2018 at 22:47
2

This answer uses xsv instead of awk, but is useful if you have many columns:

xsv cat columns <(xsv select 1-4,6- input.csv) <(xsv select 5 input.csv) > output.csv

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .