Swap first and second columns in a CSV file

7,697

Solution 1

Here you go:

awk -F, '{ print $2 "," $1 }' sampleData.csv 

Solution 2

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
$

Solution 3

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
Share:
7,697

Related videos on Youtube

Dave
Author by

Dave

Updated on September 18, 2022

Comments

  • Dave
    Dave over 1 year

    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?

  • Kusalananda
    Kusalananda almost 6 years
    Set OFS to get commas in the output too.
  • ygreaney
    ygreaney almost 6 years
    And this one would leave columns 3+ alone, rather than throwing them away.