Finding index number of a column in a csv file, but command doesnt show result? Finding index number of a column in a csv file, but command doesnt show result? shell shell

Finding index number of a column in a csv file, but command doesnt show result?


Use egrep -o to get the start of the line and count the semicolon:

echo 'TotalReported;Deceased;City' | egrep -o '.*Deceased' | sed -e 's/[^;]//g' | wc -c

The output is 2 because Deceased is in the second column.


Could you please try following, written and tested with shown samples only.

awk 'BEGIN{  FS=";"}{   gsub(/\r/,"")  for(i=1;i<=NF;i++){     if($i=="Deceased"){        print "Index is:"i        exit     }  }}' Input_file

OR in case your string could be anything then you could create an awk variable named strSearch and could assign its value as per your string which you want to look for its index.

awk -v strSearch="Deceased" 'BEGIN{  FS=";"}{  gsub(/\r/,"")  for(i=1;i<=NF;i++){     if($i==strSearch){        print "Index is:"i        exit     }  }}' Input_file

Output will be as follows.

Index is:7


echo "Date_of_report;Municipality_code;Municipality_name;Province;Total_reported;Hospital_admission;Deceased" | awk -F';' '{ for(i=1; i<=NF; i++) if($i=="Deceased") {print i} exit}'

This prints '7'.Note semicolon, not comma.