Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

csv/array problem

Status
Not open for further replies.

crichmond

Programmer
Sep 10, 2008
1
US
Hello, I am new to awk and I am having a hard time figuring out how do get this to work:

I want to process a csv file and write each column value out to a file, so i wrote this script:

awk'{

for(i=1;i<NF;i++){
ct[$1]+=1
}

for(val in ct){
print val
}
}' FS="," < mydata.csv


Now that runs and prints out to the screen, but the order it prints things out is not the order they are read in the columns....so how do i print out in the sam order they are read in?

I tried for the second loop(instead of w in ct):

for(j=0;j<NF;j++){
print ct[$j]
}

but that just prints 1 repeadetly on each line.

I feel it is somethign simple I am missing but have not been able to solve it.

What should I be doing?

Thanks,

CR
 
I think you meant ct[$i]+=1? Otherwise why have a for loop.

The other thing is that your entire code block between { and } is executed for each line of input, so the data stored in the ct array from processing the first line is still there when you are processing the second line, meaning that it is output again.

If you just want to print the column contents there's no need to assign the values to an array, just use:

Code:
awk '{for (i=1;i<=NF;i++) { print $i } }' FS=, mydata.csv

Note that I used <=NF, otherwise it would not print the last field.

Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top