Reading Files
There are a number of commands you can use to quickly read the contents of a file without having to open the file in a text editor. But, for now:
- Create a file on your Desktop called
lorem.txt
and open it in your favourite plain-text editor. - Copy the following text into the file and save it.
Now, back to your terminal, you can attempt to read the contents of this file using 2 different commands:
The first one is the less
command:
less lorem.txt
This opens a preview of the file in your terminal. You can scroll up and down using your keyboard.
When you're done, press q
to quit and go back to your terminal.
The second one is the cat
command:
cat lorem.txt
Which prints the contents of the file to the terminal directly.
Note:
This command actually has more uses than just reading files - it is short for concatenate
, and is used mainly for joining the contents of two files together.
Did you know you can be quite specific about what to print from the file?
head lorem.txt
Will show you the first 10 lines of the file.
tail lorem.txt
Will show you the last 10 lines of the file.
If you want to see more or less than the default 10 lines, you can pass the number in as a switch.
tail -3 lorem.txt
Will print the last 3 lines and the same would work with head
.
Another note, because we love them:
tail
also has a cool feature where it will keep watching a file for any new content added to the end.
If you are on a Mac run the following command:
tail -f /private/var/log/system.log
This is a log file of some of the processes that your computer is running. If you open or close an application (just open a new browser window, for example), you should see the output being updated. This can be a useful tool when you are running a program and want to see what's happening internally.
To stop following the log file, just use ctrl + c
.