Chapter 4: Viewing and Editing Files in Linux

Viewing and Editing Files in Linux

In this chapter, we’ll cover the core commands for examining and modifying text files directly in the terminal. Viewing and editing files is very useful and common as there are bunch of configuration files that you frequently need to make changes in. When you are using shell you don’t have the luxury of rich text editors like word or notepad++.

1. cat – Display File Contents

The cat (concatenate) command shows file contents in the terminal.

Basic Usage:

cat filename.txt

Common Options:

  • -n – Show line numbers
  • -b – Number only non-empty lines

Example:

cat -n config.conf

2. less/more – Scroll Through Text

For large files, use these pagers to view content page by page.

less (recommended):

less large_file.log
  • Navigation:
    • Space – Next page
    • b – Previous page
    • /pattern – Search forward
    • q – Quit

more (older alternative):

more large_file.log
  • Less features than less (ironically)
  • Automatically exits at end of file

3. head/tail – View File Beginnings/Ends

Quickly check the start or end of files.

head (first 10 lines by default):

head filename.log
head -n 20 filename.log  # Show first 20 lines

tail (last 10 lines by default):

tail filename.log
tail -n 15 filename.log  # Show last 15 lines
tail -f live.log        # Follow growing file (great for logs)

4. Terminal Text Editors

nano (Beginner-Friendly)

Simple, intuitive editor with on-screen help.

nano document.txt
  • Basic Controls:
    • Ctrl+O – Save
    • Ctrl+X – Exit
    • Ctrl+K – Cut line
    • Ctrl+U – Paste

vi/vim (Power User Editor)

The classic modal editor with steep learning curve but powerful features.

vi document.txt
  • Basic Workflow:
    1. Press i to enter Insert mode
    2. Edit text
    3. Esc to return to Command mode
    4. :wq to save and quit

5. echo – Print or Write Text

Useful for quick output and file creation.

Print to Terminal:

echo "Hello World"

Write to File:

echo "New content" > file.txt    # Overwrite
echo "Added line" >> file.txt   # Append

Summary Cheat Sheet

CommandDescription
cat fileShow entire file
less fileScroll through file
head -n 5 fileShow first 5 lines
tail -f logFollow live log
nano fileSimple text editor
vi fileAdvanced text editor
echo "text" > fileCreate/overwrite file