9. Viewing Files: cat, less, more, head, tail
Before diving into editors, knowing how to quickly inspect file content is essential.
1. Concatenate and Display (cat)
cat (concatenate) displays the entire content of a file to the terminal screen.
bash
Create a dummy file
$ echo 'Line 1 Line 2 Line 3' > example.txt
Display content
$ cat example.txt Line 1 Line 2 Line 3
If the file is very large, cat will flood your screen, which can be inconvenient.
2. Pagers for Large Files (less and more)
Pagers allow you to view content one screenful at a time. less is generally preferred over more as it allows backward navigation.
bash
View a large system file using less
$ less /etc/motd
Inside less:
Press SPACE to move down one page.
Press 'b' to move back one page.
Press 'q' to quit.
3. Viewing File Extremities (head and tail)
head: Displays the beginning (top) lines of a file.tail: Displays the ending (bottom) lines of a file (useful for logs).
By default, both display the first/last 10 lines. Use the -n flag to specify a count.
bash
Show the first 5 lines
$ head -n 5 logfile.log
Show the last 20 lines
$ tail -n 20 error.log
Watch a file in real-time (useful for live logs)
$ tail -f access.log