Lesson  in  Test Linux for DevOps Engineers

Viewing File Contents

Discover how to view files, page through them and view just the beginning or end of files.

Displaying and Paging Through Files (cat, less)

🎯 Learning Objective

Master the essential file viewing commands cat and less to efficiently display file contents, navigate through large documents, and search for specific information within files.

📚 Concept Introduction

File viewing is one of the most fundamental tasks in Linux system administration and daily server use. Whether you're examining configuration files, reading log files to troubleshoot issues, or reviewing documentation, you need reliable ways to display file contents without modifying them.

Think of file viewing tools like different ways of reading a book - cat is like flipping through a small pamphlet where you can see all pages at once, while less is like reading a thick novel where you turn pages one at a time, bookmark your place, and can easily search for specific passages. Each tool serves different purposes depending on the size and nature of what you're reading.

📁 Pre-created for this unit:

  • sample_log.txt - Sample log file for practice
  • long_document.txt - Large file for pagination practice

📄 Quick File Display with cat

The cat command (short for "concatenate") is the simplest way to display file contents. It reads files and outputs their entire contents directly to your terminal, making it perfect for small files where you want to see everything immediately.

◆ Basic File Viewing

View a single file:

cat sample_log.txt

This command reads the entire file and displays it in your terminal. The content appears immediately, and you can see all lines at once. This is ideal for configuration files, small scripts, or any content that fits comfortably on your screen.

◆ Multiple File Display

View multiple files:

cat sample_log.txt sample_log.txt

This shows both files one after another, concatenating their contents. This feature is particularly useful when you want to combine the contents of several related files, such as multiple log files from the same application or configuration fragments that belong together.

◆ Enhanced Display Options

cat provides several options to make file content more readable and informative:

Common cat options:

OptionPurposeUse Case
-nNumber all linesCode review, referencing specific lines
-bNumber non-blank lines onlyClean numbering without counting empty lines
-sSqueeze multiple blank lines into oneCleaner display of files with excessive spacing

Example with line numbering:

cat -n sample_log.txt

Line numbers are incredibly useful when you need to reference specific lines in documentation, discuss code with colleagues, or troubleshoot issues where error messages reference line numbers.

◆ When to Use cat

cat is most effective for:

  • Small files - Content that fits on one or two screens
  • Quick previews - When you need to see file contents immediately
  • Configuration files - Short system configuration files
  • Code snippets - Brief scripts or code fragments

Important limitation: Avoid using cat on large files. It dumps everything at once, which can flood your terminal and make it difficult to read specific information. For long content, use less instead.

less is a powerful pager program that allows you to view file contents one screen at a time. Unlike cat, which displays everything immediately, less gives you complete control over navigation, searching, and viewing large documents efficiently.

◆ Basic File Navigation

Open a file:

less long_document.txt

When you open a file with less, you enter an interactive viewing mode where you can navigate through the content using various keyboard commands. The content is displayed one screen at a time, making it easy to read large files without overwhelming your terminal.

◆ Essential Navigation Commands

Movement and scrolling:

KeyActionUse Case
Space or fNext pageMove forward through document
bPrevious pageGo back to review earlier content
Arrow keys, j, kMove line by linePrecise navigation for detailed reading
gGo to startJump to beginning of file
GGo to endJump to end of file
qQuit lessReturn to command prompt

◆ Powerful Search Capabilities

One of less's most valuable features is its ability to search through file contents:

Search commands:

CommandPurposeExample
/patternSearch forward/error finds next occurrence of "error"
?patternSearch backward?warning finds previous "warning"
nNext matchContinue searching in same direction
NPrevious matchSearch in opposite direction

Practice with navigation: Try opening long_document.txt, press G to go to the end, then g to go back to the top. This demonstrates how quickly you can navigate through large files.

◆ Practical Search Exercise

Task: Using less to Find Information

Let's use less on sample_log.txt to practice searching:

  1. Open sample_log.txt using less
  2. Inside less, search forward for the text DB failed
  3. Observe the line containing the match
  4. Press q to quit less

This workflow demonstrates how less excels at finding specific information in files, especially log files where you're looking for particular error messages or events.

◆ Why less is Superior for Large Files

less provides several advantages over cat for large files:

  • Memory efficient - Only loads one screen of content at a time
  • Interactive navigation - Full control over viewing position
  • Search functionality - Find specific content quickly
  • No terminal flooding - Prevents overwhelming your screen with too much text
  • Resume capability - Can return to previous viewing position

📋 Essential Command Reference

CommandPurposeBest Use Case
cat filenameDisplay entire fileSmall files, quick previews
cat -n filenameDisplay with line numbersCode review, line references
cat -b filenameNumber non-blank linesCleaner numbering for formatted text
cat file1 file2Display multiple filesCombining related content
less filenameInteractive file viewingLarge files, detailed reading
/pattern (in less)Search forwardFinding specific information
g / G (in less)Go to start/endQuick navigation to file boundaries

💡 Key Takeaways

File viewing with cat and less provides essential capabilities for examining file contents without modification, with each tool optimized for different scenarios and file sizes. The cat command excels at displaying small files quickly and completely, making it perfect for configuration files, scripts, and brief documents where you want immediate visibility of all content. The less command provides sophisticated navigation and search capabilities for large files, offering memory-efficient viewing, interactive scrolling, and powerful search functionality that makes it invaluable for examining log files, documentation, and any substantial text content.

Understanding when to use each tool - cat for quick, complete display of small files and less for controlled navigation of large files - enables efficient file examination workflows essential for system administration, troubleshooting, and daily Linux usage. Mastering less's search capabilities with forward (/pattern) and backward (?pattern) search, combined with navigation commands, provides powerful tools for finding specific information within large documents quickly and efficiently.

Viewing Specific Parts of Files (head, tail)

🎯 Learning Objective

Master the head and tail commands to efficiently view specific portions of files, monitor real-time file changes, and work with file content selectively without loading entire documents.

📚 Concept Introduction

While cat and less help you view entire files, there are many situations where you only need to see specific portions - the beginning or end of a file. This is particularly common in system administration, log analysis, and data processing scenarios.

In servers, this selective viewing becomes essential when dealing with massive log files where you only care about recent entries, or configuration files where the important settings are at the top.

📁 Pre-created for this unit:

  • sample_log.txt - Sample log file for practice
  • long_document.txt - Large file for head/tail operations

🔼 Viewing File Beginnings with head

The head command displays the first lines of a file, making it perfect for quickly examining file headers, checking file formats, or previewing the start of large documents without loading the entire content.

◆ Basic File Head Display

View first 10 lines (default):

head long_document.txt

By default, head shows the first 10 lines of a file. This default is chosen because it typically provides enough context to understand the file's structure and content without overwhelming your screen.

◆ Custom Line Count Display

Show specific number of lines:

head -n 3 long_document.txt

Alternative shorthand syntax:

head -3 long_document.txt

Example output:

This is line number 1 in the long document.
This is line number 2 in the long document.
This is line number 3 in the long document.

Both commands show just the first 3 lines. The -n option gives you precise control over how much of the file beginning you want to see. This is invaluable when you know exactly how many lines contain the information you need, such as reading CSV headers, configuration file comments, or script documentation.

🔽 Viewing File Endings with tail

The tail command displays the last lines of a file, which is essential for checking recent log entries, monitoring file updates, and examining the conclusion of documents or data files.

◆ Basic File Tail Display

View last 10 lines (default):

tail long_document.txt

The default 10-line display is perfect for checking recent activity in log files, seeing the latest entries in data files, or examining how a document or script concludes. This default strikes a balance between providing useful context and keeping the output manageable.

◆ Custom Line Count Display

Show specific number of lines:

tail -n 4 long_document.txt

Alternative shorthand syntax:

tail -4 long_document.txt

These commands display the last 4 lines, giving you precise control over how much recent content you want to examine.

◆ Real-Time File Monitoring

Monitor file changes live:

tail -f long_document.txt

The -f (follow) option transforms tail into a powerful real-time monitoring tool. When you use tail -f, the command continues running and automatically displays new lines as they're added to the file. This is invaluable for:

  • Log monitoring - Watch system logs for errors or events in real-time
  • Application debugging - Monitor application output as it runs
  • Process tracking - Follow the progress of long-running operations
  • System administration - Keep an eye on critical system files

◆ Practical Real-Time Monitoring Exercise

Demonstration workflow:

  1. Start monitoring in one terminal:
    tail -f long_document.txt
    

    You'll see the current end of long_document.txt, and the command will continue running, waiting for new content.
  2. Add content in another terminal:
    echo "NEW ACTIVITY: User login detected." >> /home/laborant/long_document.txt
    
  3. Observe real-time update - The new line immediately appears in your monitoring terminal, demonstrating how tail -f provides instant feedback on file changes.

To stop monitoring: Press Ctrl+C to exit tail -f and return to the command prompt.

This real-time capability makes tail -f one of the most important tools for system administrators and developers who need to monitor ongoing processes and system activity.

📋 Essential Command Reference

CommandPurposeBest Use Case
head filenameShow first 10 linesQuick file preview, check headers
head -n N filenameShow first N linesPrecise line control, specific needs
head -N filenameShow first N lines (shorthand)Quick syntax for common operations
tail filenameShow last 10 linesCheck recent entries, file endings
tail -n N filenameShow last N linesPrecise control over recent content
tail -N filenameShow last N lines (shorthand)Quick syntax for recent data
tail -f filenameFollow file in real-timeLog monitoring, live system tracking

💡 Key Takeaways

The head and tail commands provide essential capabilities for selective file viewing, enabling efficient examination of specific file portions without the overhead of loading complete documents. The head command excels at displaying file beginnings, making it perfect for checking configuration file headers, data file formats, script documentation, and quickly understanding file structure and content organization. The tail command specializes in showing file endings and provides powerful real-time monitoring capabilities through its -f option, making it indispensable for log analysis, system monitoring, and troubleshooting scenarios where you need to observe ongoing file changes. The real-time monitoring capability of tail -f transforms it from a simple file viewer into a critical system administration tool for continuous observation.

Understanding when to use head for file structure analysis and tail for recent activity monitoring, combined with mastery of the real-time follow functionality, provides powerful tools for efficient file content examination and system monitoring workflows essential in Linux environments.