>_ IzzyLab

Hands-on task

This task is step 13 of the course “Bash: expansions, arrays and quoting”

Parsing CSV by columns

medium~10 min

In /root/people.csv the lines are of the form name,age,city. Write /root/names.sh that outputs only the names (the first column), and save the output to /root/names.txt. Skip the header line. Keep in mind: names may contain spaces, and the file's last line doesn't end with a newline.

What you'll practise:
  • csv parsing
  • ifs variable
  • while read
  • tail
  • fields and separators

Topic breakdown

Parsing structured text in bash is built around the IFS (Internal Field Separator) variable — it defines which characters read treats as field boundaries; by setting it to a comma, you can split a CSV line into several variables, one per column, at once. Assigning IFS right in the while ... read loop header affects only that read and doesn't spoil the environment. It's convenient to cut off the header line before the loop by feeding it not the whole file but its tail starting from the second line — this is done by tail with a starting line specified. The result is redirected to a file via >.

What's checked

  1. names.txt has all the names from the CSV
  2. names are present, header is skipped
  3. names.sh also works on a different CSV

What it looks like