Skip to main content
4 of 5
deleted 5 characters in body
John1024
  • 76.4k
  • 12
  • 176
  • 165

This answer assumes that your csv file has one line per row, meaning that there are no continued lines. If the file is called db.csv, then you can get 10 lines, including the first and the last by using:

awk 'FNR==NR{next} FNR==1{n=(NR-1)} FNR>x || FNR==n{x+=n/9;print}' db.csv db.csv

How it works

Because the csv file is listed twice on the command line, awk will read through it twice. The first is used to get the total number of lines. The second time is used to print the 10 selected lines.

  • FNR==NR{next}

    NR is the total number of records (lines) read so far.The file record number, FNR, is equal to the total number of records (lines) read so far from this file. So, when FNR==NR, we are still reading the first file. If so, we just jump to the next record.

  • FNR==1{n=(NR-1)}

    If we reach this command, that means that we are on the first line of the second read through. In that case, we know that the total number of records in the file is NR-1. We save this number as n.

  • FNR>x || FNR==n{x+=n/9;print}

    One the first line of the second read through, FNR==1 and x=0. Thus, FNR>x and we print that line and increment x by incr. We then increment x by n/9 and print the the line the next time that FNR>x and so on.

    The condition FNR==n assures that the last line in the file will be printed.

Example

Let us create a file with 101 lines:

$ seq 101 >db.csv

Now, we can use our awk command to print 10 lines from the file, including the first and last:

$ awk 'FNR==NR{next} FNR==1{n=(NR-1)} FNR>x || FNR==n{x+=n/9;print}' db.csv db.csv
1
12
23
34
45
57
68
79
90
101
John1024
  • 76.4k
  • 12
  • 176
  • 165