Count columns in csv in gnuplot

gnuplot

Solution

As of gnuplot4.6, you can make a little hack script to do this. It is certainly not the most efficient, but it is pure gnuplot:

#script col_counter.gp
col_count=1
good_data=1
while (good_data){
   stats "$0" u (valid(col_count))
   if ( STATS_max ){
      col_count = col_count+1
   } else {
      col_count = col_count-1
      good_data = 0
   }
}

Now in your main script,

call "col_counter.gp" "my_datafile_name"
print col_count   #number of columns is stored in col_count.

This has some limitations -- It will choke if you have a column in the datafile that is completely non-numeric followed by more valid columns for example, but I think that it should work for many typical use cases.

print col_count

As a final note, you can use the environment variable `GNUPLOT_LIB` and then you don't even need to have `col_counter.gp` in the current directory.

Problem

Is there a function in gnuplot which returns the number of columns in a csv file? I can't find anything in the docs, maybe someone can propose a custom made function for this?

Original source

Related problems