This page explores commands for viewing large files and searching for patterns within file content.
11. less
- Paged File Viewer (Forward and Backward)
Purpose: The less
command is a powerful file viewer that allows you to view file contents one page at a time. Unlike more
, it allows both forward and backward navigation, making it ideal for large files.
Syntax: less [OPTIONS] FILE...
Key Navigation:
- Spacebar or
f
: Scroll forward one page. b
: Scroll backward one page.- Arrow keys (Up/Down): Scroll line by line.
/pattern
: Search forward for a pattern.?pattern
: Search backward for a pattern.n
: Go to the next match (after searching).N
: Go to the previous match (after searching).q
: Quitless
.
Examples:
less /var/log/syslog less large_config.txt
12. more
- Paged File Viewer (Forward Only)
Purpose: The more
command is another file viewer that displays content one screen at a time. It's simpler than less
, primarily allowing forward movement through the file.
Syntax: more [OPTIONS] FILE...
Key Navigation:
- Spacebar: Scroll forward one page.
- Enter: Scroll forward one line.
q
: Quitmore
.
Examples:
more /etc/services more long_readme.md
13. head
- Display the Beginning of a File
Purpose: The head
command displays the first few lines of a file. By default, it shows the first 10 lines.
Syntax: head [OPTIONS] FILE...
Key Options:
-n NUM
: Displays the first NUM lines.
Examples:
head my_log.txt head -n 5 configuration.ini
14. tail
- Display the End of a File
Purpose: The tail
command displays the last few lines of a file. By default, it shows the last 10 lines. It's often used for monitoring log files.
Syntax: tail [OPTIONS] FILE...
Key Options:
-n NUM
: Displays the last NUM lines.-f
: (follow) Outputs appended data as the file grows. Excellent for real-time log monitoring.
Examples:
tail access.log tail -n 20 error.log tail -f /var/log/messages
15. grep
- Search for Patterns in Files
Purpose: The grep
command (Global Regular Expression Print) searches for lines matching a specified pattern in one or more files.
Syntax: grep [OPTIONS] PATTERN [FILE...]
Key Options:
-i
: (ignore case) Performs a case-insensitive search.-v
: (invert match) Displays lines that DO NOT match the pattern.-r
or-R
: (recursive) Searches directories recursively.-n
: (line number) Displays the line number along with the matching line.-c
: (count) Displays only a count of matching lines.
Examples:
grep "error" /var/log/syslog grep -i "warning" myapp.log grep -r "TODO" ~/projects/ grep -n "function main" program.c