Linux Basics: Reading and Searching Text Files
You can inspect a text file on Debian or Ubuntu without opening an editor. Start with a small practice file, then use the same commands on larger files.
Create sample text
Run mktemp -d, then use cd to enter the directory it prints. Inside that new directory, run:
printf 'Started\nWarning: retrying\nFinished\n' > sample.logprintf writes text, and \n starts a new line. The shell’s > saves the output to a file. It overwrites that file if it already exists, so use the new practice directory.
Read all or part of a file
cat sample.log
head -n 2 sample.log
tail -n 1 sample.logcat prints the whole file. head -n 2 prints its first two lines; tail -n 1 prints its last line.
For a larger file, use less sample.log if less is installed. Scroll with the arrow keys and press q to quit. These reading commands leave the file unchanged.
Find matching lines
grep -n 'Warning' sample.log
grep -ni 'warning' sample.log2:Warning: retrying
2:Warning: retryinggrep prints lines that match the pattern. -n adds line numbers, and -i ignores letter case.
No matching text normally means no output. It does not mean the file is empty.
To watch new lines being appended to a log, use tail -f sample.log. Press Ctrl+C to stop watching; this does not delete the file.
References
GNU Coreutils manual · grep manual
Acknowledgements
This post was created with assistance from AI.
Linux Basics — lesson 5 of 25. Series index
Previous: Creating, Copying, and Removing Files · Next: Finding Files with find