Search code examples
bashcsvcut

Bash cut .csv files


I'm working with a sample .csv file

my.csv:

1/2/09 6:17,Product1,1200,Mastercard,carolina,Basildon,England,United Kingdom,1/2/09 6:00,1/2/09 6:08,51.5,-1.1166667
1/2/09 4:53,Product1,1200,Visa,Betina,Parkville                   ,MO,United States,1/2/09 4:42,1/2/09 7:49,39.195,-94.68194
1/2/09 13:08,Product1,1200,Mastercard,Federica e Andrea,Astoria                     ,OR,United States,1/1/09 16:21,1/3/09 12:32,46.18806,-123.83
1/3/09 14:44,Product1,1200,Visa,Gouya,Echuca,Victoria,Australia,9/25/05 21:13,1/3/09 14:22,-36.1333333,144.75
1/4/09 12:56,Product2,3600,Visa,Gerd W ,Cahaba Heights              ,AL,United States,11/15/08 15:47,1/4/09 12:45,33.52056,-86.8025
1/4/09 13:19,Product1,1200,Visa,LAURENCE,Mickleton                   ,NJ,United States,9/24/08 15:19,1/4/09 13:04,39.79,-75.23806
1/4/09 20:11,Product1,1200,Mastercard,Fleur,Peoria                      ,IL,United States,1/3/09 9:38,1/4/09 19:45,40.69361,-89.58889
1/2/09 20:09,Product1,1200,Mastercard,adam,Martin                      ,TN,United States,1/2/09 17:43,1/4/09 20:01,36.34333,-88.85028
1/4/09 13:17,Product1,1200,Mastercard,Renee Elisabeth,Tel Aviv,Tel Aviv,Israel,1/4/09 13:03,1/4/09 22:10,32.0666667,34.7666667
1/4/09 14:11,Product1,1200,Visa,Aidan,Chatou,Ile-de-France,France,6/3/08 4:22,1/5/09 1:17,48.8833333,2.15

I'm trying to print out data using cut -d"," -f-6 my.csv but this only prints the first row:
1/2/09 6:17,Product1,1200,Mastercard,carolina,Basildon

How do I get cut to print the entries of every row matching the delimiter/field?


Solution

  • Given your example:

    $ awk -F, '{print $6}' file
    Basildon
    Parkville                   
    Astoria                     
    Echuca
    Cahaba Heights              
    Mickleton                   
    Peoria                      
    Martin                      
    Tel Aviv
    Chatou
    

    Or with cut:

    $ cut -d, -f 6 file 
    # same output
    

    Or, for all fields up to and including the 6th:

    $ awk 'BEGIN{FS=OFS=","} {for (i=1;i<=6;i++) printf "%s%s", $i, i==6 ? ORS : OFS}' file
    

    Or, cut version:

    $ cut -d, -f-6 file