7.4 Exercises

7.4.1 Text Files

See Section 12.0.10 for solutions.

  1. Use a for loop to create a file myFile.txt with 1000 lines reading This is line 1, This is line 2, …, This is line 1000.

  2. Use moreand less to browse through your file myFile.txt.

  3. Use cut to extract the 4th column of myFile.txt that contains the line numbers.

  4. Use head to extract the first 7 lines of myFile.txt and store them in a new file myShortFile.txt. Then use tailto add the last 7 lines of myFile.txt to myShortFile.txt;

  5. Use wc to confirm that myShortFile.txt has only 14 lines.

  6. Use cut and tail to extract the second column (the one containing “is”) of the last 17 lines of myFile.txt.

  7. Use cat to create a new file header.txt that contains the header line “A file with numbered lines”, followed by the contents of myFile.txt.

  8. Use tail to extract all but the first line of header.txt and store these in a new file myFile2.txt. Use wc to check that it has the same number of lines as myFile.txt and also confirm visually with head and tail that the two files have the same lines at the beginning and end.

  9. Use cmp to ensure that myFile.txt and myFile2.txt are identical.