Viewing and Searching Text in the Terminal
A practical guide to viewing text files, inspecting selected lines, searching with grep, and interpreting search results.
View a Whole File or Selected Parts
Choose how to view the file
For a short file, notes.txt writes its contents to the terminal. It copies the text to standard output without adding page breaks or interpreting it. You can supply multiple filenames; their contents appear in order. Because long output may scroll past, is convenient when you need to browse a lengthy file.
For that, use system.log. It shows one screen at a time, and you can move with the arrow keys or Page Up and Page Down. To search forward, type /word and press Enter; press n for the next match, and q to quit. Unlike , lets you move around without dumping the entire file to the screen.
Inspect the beginning or end
head prints the first 10 lines by default; tail prints the last 10. Specify another number with -n: head -n 5 system.log shows the first five lines, while tail -n 20 system.log shows the last twenty. To keep displaying text as it is appended to a log, use tail -f system.log.
Search for Matching Lines
Select lines by pattern
prints each line that matches the pattern. For example, 'error' system.log selects lines containing error.
Options change what reports:
-iignores uppercase/lowercase differences.-ndisplays line numbers for matching lines.-cprints the number of matching lines instead of printing the lines themselves.
Combine options when useful: -in 'error' system.log prints matching lines with their line numbers and ignores case. By default, interprets patterns as regular expressions, so some characters have special meanings. Quoting the pattern, as in these examples, prevents the shell from interpreting it; it does not make ’s pattern cease to be a .
Understand Counts, Empty Results, and Errors
Know what a count measures
A match is a selected line. Therefore, -c 'error' system.log counts lines containing a match, not every occurrence of error within those lines. To count newline characters in a file, use system.log. These counts can differ: counts newline characters, so a final line without a terminating newline may not be included.
Interpret no output
If prints nothing, it may simply have found no matching lines. For GNU , exit status 0 means it selected at least one line, 1 means it selected none, and 2 means an error occurred—for example, the file could not be read. Thus, no printed matches do not by themselves show that the file is empty or that the command failed. Check the pattern, filename, and spelling, and distinguish a no-match status from an error status.
: Commands that display the beginning or end of a file.
: A result selected by a search pattern; counts selected lines, not necessarily every occurrence of text.