Bash: How to Read CSV File and Skip First Line


Often you may want to use Bash to read the lines from a CSV file but skip the first line in the file because it’s a header or you simply don’t need it.

You can use the following syntax to do so:

while read line
do
   echo "Player Info: $line"
done < <(tail -n +2 nba_data.csv)

This particular example reads all lines from the CSV file named nba_data.csv but skips the first line.

Note that we used tail -n +2 to specify that we want to read all lines in the file starting from line 2.

This allows us to skip the first line when reading the lines from the file.

The following example shows how to use this syntax in practice.

Example: How to Read CSV File and Skip First Line in Bash

Suppose that we have a file named nba_data.csv.

We can use the cat statement to view the contents of this file:

This file contains information about the team, points scored and total assists for various basketball players.

Notice that the first row is simply a header row that contains the values team, points and assists.

Suppose that we would like to read each of the lines in this CSV file but skip the first header row.

We can use the following syntax to do so:

while read line
do
   echo "Player Info: $line"
done < <(tail -n +2 nba_data.csv)

The following screenshot shows how to use this syntax in practice:

Bash read CSV file skip first line

Notice that Bash reads each row from the file and skips the first header row.

We specified that each line should be prefixed with “Player info:” but you can choose to use any prefix that you would like.

Also note that if you need to skip multiple lines in the beginning of the CSV file then you can change the 2 to a different number after the tail command.

For example, we could use the following syntax to start reading the rows from the CSV file starting at row 3 instead:

while read line
do
   echo "Player Info: $line"
done < <(tail -n +3 nba_data.csv)

The following screenshot shows how to use this syntax in practice:

Bash read CSV skip first n lines

This time we’re able to read the rows starting from row 3 and we’re able to skip the first 2 rows.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Replace Special Characters in String
Bash: How to Replace Specific Line in File
Bash: How to Replace All Occurrences of String in File

Leave a Reply