Search

Liko Learns Linux, Episode 3 — Read and Search Files with cat, head, tail, and grep

You’ve learned how to create, copy, rename, and delete files in Linux. In Episode 3 of Liko Learns Linux, you’ll learn how to look inside a text file, preview its first or last few lines, and find the lines that contain a particular word.

Set up the practice file

In a practice folder, use a text editor to save these eight lines as linux_notes.txt. Then open a terminal in the same folder.

Linux makes command-line work easier.
Practice in a separate folder.
Use short, descriptive filenames.
Keep a copy of important notes.
Read a file before editing it.
Linux tools can search text.
Check your results as you go.
Try one new command today.

1. Display the whole file with cat

cat linux_notes.txt

This displays all eight lines in the terminal. Try it when you want to read a short file from start to finish.

2. Show the first three lines with head

head -n 3 linux_notes.txt

The option -n 3 tells head to display three lines from the beginning of the file.

Linux makes command-line work easier.
Practice in a separate folder.
Use short, descriptive filenames.

3. Show the last three lines with tail

tail -n 3 linux_notes.txt

tail uses the same -n option but reads from the end of the file.

Linux tools can search text.
Check your results as you go.
Try one new command today.

4. Find matching lines with grep

grep "Linux" linux_notes.txt

grep prints each line containing the search text. This search is case-sensitive, so it matches Linux with a capital L.

Linux makes command-line work easier.
Linux tools can search text.

Try it yourself

Change -n 3 to -n 2 in either head or tail. Then search for "file" with grep. Does it also find a line containing filenames?

Follow Liko Learns Linux for more hands-on terminal lessons.

No comments:

Post a Comment