2

I've have an awk script in terminal where it performs some counting function:

awk '{ a[$2]++ }END{ for(i in a) printf "%-15s%s\n",i,a[i] }'   
Data_1

and i plan to output as a csv file where i add

awk '{ a[$2]++ }END{ for(i in a) printf "%-15s%s\n",i,a[i] }'    
Data_1 > Count.csv

but the problem I'm facing now is, the awk script above outputs

Gregor   4
Alexis   15
George   17

and after outputting as a csv file, the name and count is appended to only one column A in excel. How would i format the csv command in terminal to specify the name to have one column and the number in another column? In excel I want to obtain

A         B
Gregor    4
Alexis    15
George    17
2
  • Try adding OFS into your code.
    – mathB
    Oct 18, 2017 at 4:18
  • What symbol do you use as delimeter in csv? Oct 18, 2017 at 5:14

1 Answer 1

3

You need add a comma between fields to have simple .csv type format when you are using with printf.

awk '{ a[$2]++ }END{ for(i in a) printf "%-15s,%s\n",i,a[i] }'
Gregor    ,4
Alexis    ,15
George    ,17

Or full-fledged .csv type

awk '{ a[$2]++ }END{ for(i in a) printf "\"%-15s\",\"%s\"\n",i,a[i] }'
"Gregor    ","4"
"Alexis    ","15"
"George    ","17"

But you could use print instead and let awk add comma with OFS (simple .csv).

awk '{ a[$2]++ }END{ for(i in a) print i,a[i] }' OFS=,
Gregor,4
Alexis,15
George,17

Or just print it within fields itself.

awk '{ a[$2]++ }END{ for(i in a) print i","a[i] }'
Gregor,4
Alexis,15
George,17

For full-fledged .csv format.

awk '{ a[$2]++ }END{ for(i in a) print "\""i"\",\""a[i]"\"" }'
"Gregor","4"
"Alexis","15"
"George","17"

You must log in to answer this question.

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