head and tail on Unix

3.1k Views Asked by At

My second homework assignment asks for us to write a command in Unix or Linux to extract certain sections of multiple files using head and tail. I'm not understanding how to go about this. Here is the question:

(5 points) Using head and tail, write a command to extract the second section of a file (i.e. the data section). Turn this into an executable script called extractdata (you do not need to hand this in). Then use find and extractdata, write a command to get the second section of all .csv files in the month directories, and place the output into a file called polls.csv. Be sure to keep this file in your homedir. You will use it again on the next assignment. [hint] Inside the script don't forget the command line variable $1. example: head -52 $1

The .csv files consist of three parts: (1) a two line header, describing the fields; (2) 51 lines representing data for each state (plus Washington DC); (3) the rest of the file is summary information. The data fields for each state in the second part is comma separated. I have to get the second section.

Thank you.

3

There are 3 best solutions below

0
On BEST ANSWER

Use head to extract the first 53 lines. Use tail to extract the last 51 lines of the result (effectively ignoring the first 2 header lines).

0
On

Take it in stages:

  • Read what head and tail both do, (get the first and last n lines)
  • think about what you need (the middle 51 lines)
  • how can you do that?
0
On

The problem I had was figuring out how to get the data from multiple .csv files. I used wild cards to solve my issue. If anyone else needed to know I used this:

head -n 53 $1 /usr/local/tmp/election2008/*/*.csv | tail -n 51 $1