7.4 Exercises
7.4.1 Text Files
See Section 12.0.10 for solutions.
Use a
forloop to create a filemyFile.txtwith 1000 lines readingThis is line 1,This is line 2, …,This is line 1000.Use
moreandlessto browse through your filemyFile.txt.Use
cutto extract the 4th column ofmyFile.txtthat contains the line numbers.Use
headto extract the first 7 lines ofmyFile.txtand store them in a new filemyShortFile.txt. Then usetailto add the last 7 lines ofmyFile.txttomyShortFile.txt;Use
wcto confirm thatmyShortFile.txthas only 14 lines.Use
cutandtailto extract the second column (the one containing “is”) of the last 17 lines ofmyFile.txt.Use
catto create a new fileheader.txtthat contains the header line “A file with numbered lines”, followed by the contents ofmyFile.txt.Use
tailto extract all but the first line ofheader.txtand store these in a new filemyFile2.txt. Usewcto check that it has the same number of lines asmyFile.txtand also confirm visually withheadandtailthat the two files have the same lines at the beginning and end.Use
cmpto ensure thatmyFile.txtandmyFile2.txtare identical.