Read a csv file by using a shell script

Here is a very simple shell script written in bash to read a csv file line by line. For information, CSV stands for “comma separated values”.

This script uses a while loop, but could work with another looping statement like ‘for’. Every line is read, and then split using the “cut” command by specifiying the separator. In the case below, a semi colon was used as field separator.

The example works fine but is not optimized for big files, because each “cut” statement takes time to be executed. Everything depends on volumes manipulated. These useful functions should be used with care.


while read line
        echo '-----------------------------'
        echo "Line :"
        echo "  $line"
        field1=`echo $line |cut -d';' -f1`
        field2=`echo $line |cut -d';' -f2`
        field3=`echo $line |cut -d';' -f3`

        echo "  Field1: ${field1} - Field2: ${field2} - Field3: ${field3}"
done < datafile.csv

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post