>_ IzzyLab

Hands-on task

This task is step 1 of the course “First steps with text”

Split the table header from the data

easy~4 min

/root/data/prices.csv is a shop's price list. The first line is the header: the column names. After it comes one line per item.

  1. Save the header (only the first line) to /root/header.txt.
  2. Save all the item lines — everything except the header, in the same order — to /root/rows.txt.

Don't change prices.csv itself.

What you'll practise:
  • cat
  • head -n
  • tail -n
  • tail -n +N
  • CSV header

Topic breakdown

A text file is just lines, one under another. There are several ways to look at it:

  • cat file — show the whole file;
  • head -n N file — the first N lines;
  • tail -n N file — the last N lines;
  • tail -n +N file — everything from line number N to the end.
head -n 3 /etc/passwd      # the first three lines
tail -n 2 /etc/passwd      # the last two
tail -n +5 /etc/passwd     # from the fifth line to the end

Tables are often stored as CSV: the values in a line are separated by commas, and the first line is a header with the column names. For counting and sorting, the header is usually cut off so it doesn't get mixed in with the data.

Instead of printing a command's output on screen, you can save it to a file with >:

head -n 3 /etc/passwd > /tmp/top.txt   # three lines went to the file, the screen stays empty

The file is created automatically; if it already existed, > overwrites it completely.

What's checked

  1. header.txt holds just the first line of the file
  2. rows.txt has no header
  3. rows.txt holds all the items, in order

What it looks like