RED HAT ENTERPRISE LINUX

Working with Text Files

Create, View, and Edit from the Command Line

CIS126RH | RHEL System Administration
Mesa Community College

Learning Objectives

1
View text file contents

Use cat, less, head, tail, and other viewing commands

2
Create text files

Use redirection, here documents, and editors

3
Edit files with vim

Navigate, insert, modify, search, and save in vim

4
Edit files with nano

Use nano for quick and simple text editing

Why Text Files Matter

In Linux, everything is configured with text files. System settings, service configurations, scripts, logs — all are plain text that you can read and edit.

Configuration Files

  • /etc/hosts — hostname mappings
  • /etc/ssh/sshd_config — SSH server
  • /etc/httpd/conf/httpd.conf — Apache
  • /etc/fstab — filesystem mounts
  • ~/.bashrc — shell configuration

Scripts and Logs

  • /var/log/messages — system log
  • /var/log/secure — security log
  • /usr/local/bin/*.sh — local scripts
  • ~/.bash_history — command history
  • Cron jobs, systemd units, etc.

The Text File Philosophy

Advantages of Text Files

  • Human-readable — understand without special tools
  • Versionable — track changes with git
  • Scriptable — generate and modify programmatically
  • Transparent — nothing is hidden

Why Command-Line Skills?

  • Servers often have no GUI
  • SSH sessions are text-only
  • Recovery situations
  • Automation and scripting
  • RHCSA exam requirement
Philosophy: Text files are human-readable, versionable, scriptable, and transparent. No proprietary formats or special tools needed.

Viewing Files: cat

cat (concatenate) displays file contents to the terminal. Best for small files — large files scroll by too quickly.
# Display file contents
[user@host ~]$ cat /etc/hostname
server.example.com

# Display multiple files (concatenates them)
[user@host ~]$ cat file1.txt file2.txt

# Show line numbers
[user@host ~]$ cat -n /etc/passwd
     1  root:x:0:0:root:/root:/bin/bash
     2  bin:x:1:1:bin:/bin:/sbin/nologin
     3  daemon:x:2:2:daemon:/sbin:/sbin/nologin
...

cat Diagnostic Options

# Show non-printing characters (useful for debugging)
[user@host ~]$ cat -A file.txt
Line with tab^Iand end$
Normal line$

# Number only non-empty lines
[user@host ~]$ cat -b file.txt
-A reveals hidden characters: tabs appear as ^I, line endings as $. Invaluable for debugging files with wrong line endings (Windows \r\n vs Linux \n) or unexpected whitespace.
Caution: cat on a large file (like a log) floods your terminal. Use less for big files. Never cat a binary file — it can corrupt your terminal display.

Viewing Files: less

less is a pager — it displays files one screen at a time, letting you scroll forward and backward. Essential for large files.
# Open file in less
[user@host ~]$ less /var/log/messages
KeyActionKeyAction
SpaceNext pagebPrevious page
↓ or jDown one line↑ or kUp one line
gGo to beginningGGo to end
/patternSearch forward?patternSearch backward
nNext search matchNPrevious match
qQuithHelp

less Tips & Options

# Open with line numbers shown
[user@host ~]$ less -N /var/log/messages

# Chop long lines instead of wrapping
[user@host ~]$ less -S /var/log/messages

# Follow file like tail -f (press F to start, Ctrl+C to stop)
[user@host ~]$ less +F /var/log/messages
Remember: Press q to quit less. Man pages use less, so these navigation keys work there too — and in journalctl and other paging tools.
The name less is a play on words — it is more capable than the older more command. The saying goes "less is more."

Viewing Files: head and tail

# Show first 10 lines (default)
[user@host ~]$ head /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
...

# Show first 5 lines
[user@host ~]$ head -n 5 /etc/passwd
[user@host ~]$ head -5 /etc/passwd      # Short form

# Show last 10 lines (default)
[user@host ~]$ tail /var/log/messages

# Show last 20 lines
[user@host ~]$ tail -n 20 /var/log/secure
head is useful for checking file format or grabbing the start of a file. tail is particularly valuable for log files, where the most recent (and relevant) entries are at the end.

tail -f: Real-Time Monitoring

# Follow file in real-time (watch for new lines)
[user@host ~]$ tail -f /var/log/messages
(new lines appear as they're written)
Press Ctrl+C to stop

# Follow multiple files simultaneously
[user@host ~]$ tail -f /var/log/messages /var/log/secure
tail -f is essential for monitoring logs in real-time. Watch services start, troubleshoot errors, and observe system activity live. When following multiple files, tail shows which file each new line comes from.
Some administrators keep a terminal with tail -f running on important logs at all times during active work.

Other Viewing Commands

# wc - word count (lines, words, characters)
[user@host ~]$ wc /etc/passwd
  45   89  2567 /etc/passwd
[user@host ~]$ wc -l /etc/passwd      # Lines only
45 /etc/passwd

# grep - search for patterns
[user@host ~]$ grep "root" /etc/passwd
root:x:0:0:root:/root:/bin/bash
[user@host ~]$ grep -n "error" /var/log/messages   # With line numbers
[user@host ~]$ grep -i "ERROR" /var/log/messages   # Case insensitive
wc provides quick file statistics — use -l for line count, -w for words, -c for characters. grep is one of the most frequently used Linux commands — covered in depth in its own module.

Viewing Commands: diff and file

# diff - compare two files
[user@host ~]$ diff file1.txt file2.txt
3c3
< old line three
---
> new line three

# file - determine file type
[user@host ~]$ file /etc/passwd
/etc/passwd: ASCII text
[user@host ~]$ file /bin/ls
/bin/ls: ELF 64-bit LSB executable...
diff shows what changed between file versions — essential for configuration management. The < symbol indicates lines from the first file, > from the second.
Always use file first when you are unsure what a file contains. Binary files displayed with cat can corrupt your terminal display.

Creating Files: Redirection

Output redirection sends command output to a file instead of the screen. Use > to create/overwrite, >> to append.
# Create file with echo
[user@host ~]$ echo "Hello, World!" > greeting.txt
[user@host ~]$ cat greeting.txt
Hello, World!

# Append to existing file
[user@host ~]$ echo "Second line" >> greeting.txt
[user@host ~]$ cat greeting.txt
Hello, World!
Second line

# Create empty file with redirection
[user@host ~]$ > emptyfile.txt

Redirection: Patterns & Warning

# WARNING: > overwrites without asking!
[user@host ~]$ echo "Oops" > greeting.txt   # Previous content GONE

# Redirect any command output to file
[user@host ~]$ ls -la > directory_listing.txt
[user@host ~]$ date > timestamp.txt
Warning: > destroys existing content with no confirmation! Use >> to append safely when you want to keep what is already there.
Any command's output can be redirected. ls -la > listing.txt captures a directory listing. date > timestamp.txt records the current time. This pattern is used constantly in scripts.

Creating Files: Here Documents

Here documents let you create multi-line content inline. The content between the markers becomes the input.
# Create multi-line file with here document
[user@host ~]$ cat > config.txt << EOF
server=192.168.1.100
port=8080
enabled=true
EOF

[user@host ~]$ cat config.txt
server=192.168.1.100
port=8080
enabled=true
The syntax is command << MARKER followed by lines of content, then MARKER on its own line to end. cat > file << EOF is the standard pattern for creating files with heredocs.

Here Documents: Variable Expansion

# Unquoted marker: variables ARE expanded
[user@host ~]$ cat > script.sh << EOF
#!/bin/bash
echo "Current user: $USER"
EOF
# $USER is replaced with the actual username

# Quoted marker ('EOF'): variables are NOT expanded
[user@host ~]$ cat > script.sh << 'END'
#!/bin/bash
echo "Current date: $(date)"
echo "Current user: $USER"
END
# $USER and $(date) are written literally into the file
Important: When creating scripts with here documents, use a quoted marker ('EOF') to prevent shell expansion — otherwise $VARIABLES are replaced before being written to the file.

Introduction to vim

Why Learn vim?

  • Available on every Linux system
  • Works perfectly over SSH
  • Extremely powerful editing
  • Fast once mastered
  • Required for RHCSA exam

The Challenge

  • Modal editor (modes matter)
  • Non-intuitive for beginners
  • Keys behave differently per mode
  • No on-screen menus
  • Must learn commands
# Open or create a file with vim
[user@host ~]$ vim filename.txt

# vi is often aliased to vim
[user@host ~]$ vi filename.txt

vim Modes

vim is a modal editor. Keys behave differently in each mode. Understanding modes is the key to using vim.
ModePurposeEnter WithExit With
NORMALNavigation, commands, operatorsEsc(Default mode)
INSERTTyping and inserting texti, a, oEsc
COMMANDSave, quit, search, substitute:Enter or Esc
VISUALSelect text for operationsv, VEsc
Lost? Press Esc repeatedly to return to Normal mode. This is your safe haven — from here you can navigate, enter other modes, or quit.

vim Mode Illustration

This is some text in the file.
The cursor is blinking here._
 
 
 
NORMAL    filename.txt [+]    2,25    All

Normal Mode (default)

Status bar shows no mode indicator. Every key press is a command — not text input.

Insert Mode

Status bar shows -- INSERT --. Keys type text as you would expect.

vim: Save, Quit & Insert

Saving and Quitting

:wSave (write)
:qQuit (fails if unsaved)
:wqSave and quit
:q!Quit without saving
:wq!Force save and quit

Entering Insert Mode

iInsert before cursor
aAppend after cursor
oOpen line below
OOpen line above
AAppend at end of line
Minimum survival: i to type, Esc when done, :wq to save and quit.

vim Navigation

Basic Movement

h j k lLeft, down, up, right
wNext word
bPrevious word
0Beginning of line
$End of line

File & Page Navigation

ggFirst line of file
GLast line of file
:42Go to line 42
Ctrl+fPage forward
Ctrl+bPage backward
Arrow keys also work for navigation — h j k l are the vim-native keys that keep your fingers on the home row for speed.

vim Editing Commands

CommandActionCommandAction
xDelete char under cursorddDelete entire line
dwDelete wordd$Delete to end of line
yyYank (copy) lineywYank word
pPaste after cursorPPaste before cursor
uUndo last changeCtrl+rRedo
rReplace single charactercwChange word (delete + insert)
In vim, deleted text is also placed in the buffer — so dd followed by p effectively moves a line. u undoes; keep pressing for more undos.

vim: Counts & Repeat

# Combining commands with counts
5dd     - Delete 5 lines
3yy     - Yank 3 lines
10j     - Move down 10 lines
d5w     - Delete 5 words
2p      - Paste 2 times

# Repeat last change
.       - Repeat last editing command
Pattern: vim commands combine: [count][operator][motion]
Example: d3w = delete 3 words  |  5dd = delete 5 lines  |  . = repeat last edit

vim Search

# Search forward
/pattern    - Search forward for "pattern"
n           - Next match
N           - Previous match

# Search backward
?pattern    - Search backward for "pattern"
Type / followed by your search pattern and press Enter. vim jumps to the first match and highlights all matches. Press n to go to the next match, N for the previous.
Search patterns support regular expressions for powerful matching — e.g., /^root finds lines starting with "root", /[0-9]\+ finds numbers.

vim Search and Replace

# Replace on current line
:s/old/new/         - Replace first match on current line
:s/old/new/g        - Replace ALL on current line

# Replace in entire file
:%s/old/new/g       - Replace ALL occurrences in file
:%s/old/new/gc      - Replace all, ask for Confirmation each time

# Examples
:%s/http/https/g           - Change http to https everywhere
:5,15s/foo/bar/g           - Replace only on lines 5-15
The substitute pattern: :[range]s/search/replace/[flags]
Flags: g = global (all matches)  |  c = confirm each  |  i = case insensitive

vim Visual Mode

Visual mode lets you select text visually, then apply operations to the selection. More intuitive for some tasks.
KeySelection Type
vCharacter-wise selection (highlight characters)
VLine-wise selection (highlight entire lines)
Ctrl+vBlock selection (rectangular region)
# Visual mode workflow:
1. Position cursor at start of selection
2. Press v (or V for lines)
3. Move cursor to extend selection (highlighted)
4. Press operator: d (delete), y (yank), c (change), etc.

Visual Mode Examples

# Examples
V5jd        - Select 5 lines down, delete them
viw         - Select inner word (visual-inner-word)
va"         - Select including quotes (visual-around-")
Vjj:s/old/new/g  - Substitute only in selected lines
Tip: Visual mode is great when you're not sure exactly what you want to select — see it highlighted before acting on it.
Block selection (Ctrl+v) is powerful for editing columns of text — add or remove characters at the same position on multiple lines simultaneously.

vim Configuration

# Useful settings (use during session)
:set number         - Show line numbers
:set nonumber       - Hide line numbers
:set hlsearch       - Highlight search matches
:set nohlsearch     - Remove highlights
:set ignorecase     - Case-insensitive search
:set smartcase      - Case-sensitive if uppercase used
:set tabstop=4      - Tab width of 4 spaces
:set expandtab      - Use spaces instead of tabs
:set autoindent     - Auto-indent new lines
:set syntax=on      - Enable syntax highlighting

Persistent Config: ~/.vimrc

# Create persistent configuration
[user@host ~]$ vim ~/.vimrc
set number
set hlsearch
set ignorecase
set smartcase
set tabstop=4
set expandtab
set autoindent
syntax on
~/.vimrc is loaded every time vim starts. Put your preferred settings there for permanent configuration. Settings in .vimrc use the same names as :set commands but without the colon.

vim Practice Workflow

  1. Open file: vim /etc/hosts
  2. Navigate to line: :5 (go to line 5)
  3. Go to end of line: $
  4. Enter insert mode: a (append after cursor)
  5. Type your text…
  6. Return to normal: Esc
  7. Save and quit: :wq
Practice tip: Create a test file and experiment freely. Use :q! to quit without saving your experiments — nothing is permanent until you :w.
# Built-in vim tutorial (highly recommended!)
[user@host ~]$ vimtutor
# Takes about 30 minutes, teaches all basics interactively

Introduction to nano

nano is a simple, user-friendly text editor. It displays keyboard shortcuts on screen and works like a typical editor — no modes.
GNU nano 5.6  —  config.txt

server=192.168.1.100
port=8080
enabled=true

^G Help   ^O Write Out   ^W Where Is   ^K Cut   ^U Paste   ^X Exit
# Open or create file with nano
[user@host ~]$ nano filename.txt

# Open at specific line number
[user@host ~]$ nano +25 filename.txt

nano: Reading the Shortcuts

The ^ symbol means Ctrl. So ^X means Ctrl+X. All shortcuts are shown at the bottom of the screen — you never need to memorize them.
nano is perfect for quick edits when you do not need vim's power. It is also a good fallback on unfamiliar systems where vim may not be configured as expected.
The downside: nano lacks vim's powerful editing commands. For complex text manipulation — bulk search/replace, macros, column editing — vim is more efficient.

nano Essential Commands

ShortcutActionShortcutAction
Ctrl+OWrite Out (save)Ctrl+XExit
Ctrl+KCut lineCtrl+UPaste (uncut)
Ctrl+WWhere Is (search)Ctrl+\Search and replace
Ctrl+GHelpCtrl+CShow cursor position
Ctrl+ABeginning of lineCtrl+EEnd of line
Ctrl+YPage upCtrl+VPage down
Alt+UUndoAlt+ERedo
Ctrl+_Go to line numberAlt+GGo to line (also)

nano Workflow

# Common workflow
1. nano filename.txt     - Open file
2. (make edits directly - just type)
3. Ctrl+O, Enter         - Save
4. Ctrl+X                - Exit

# Search and replace
1. Ctrl+\                - Start replace
2. Enter search term, Enter
3. Enter replacement, Enter
4. A (for all) or Y/N for each
The workflow is simple: open → edit → Ctrl+O to save → Ctrl+X to exit. No modes to switch, no commands to memorize beyond the shortcuts shown on screen.

vim vs nano

vim Strengths

  • Extremely powerful editing
  • Very fast once learned
  • Available everywhere
  • Required for RHCSA exam
  • Macro recording
  • Extensive customization
  • Plugin ecosystem

nano Strengths

  • Immediately usable
  • On-screen help
  • No learning curve
  • Good for quick edits
  • Familiar interface
  • Less cognitive load
  • Lower risk of mistakes
Recommendation: Learn vim well — it is a career skill. Use nano for quick, simple edits when vim's power is overkill.

Setting Your Default Editor

# Set default editor for this session
[user@host ~]$ export EDITOR=vim

# Make it permanent
[user@host ~]$ echo 'export EDITOR=vim' >> ~/.bashrc
The EDITOR environment variable sets your default editor for programs that need to open one — such as crontab -e, git commit, and visudo. Set it in your .bashrc to make your preference permanent across sessions.

Key Takeaways

1

Viewing: cat for small files, less for paging, head/tail for portions. tail -f follows logs in real-time.

2

Creating: > redirects output to files. >> appends. Here documents for multi-line content.

3

vim: Modal editor — Normal (commands), Insert (typing), Command (:). i to type, Esc to stop, :wq to save.

4

nano: Simple editor with on-screen help. Ctrl+O saves, Ctrl+X exits. Good for quick edits.

Graded Lab

HANDS-ON EXERCISES

  • View /etc/passwd with cat, less, head, and tail
  • Create a configuration file using echo and redirection
  • Create a multi-line file using a here document
  • Complete vimtutor (run: vimtutor)
  • Edit a file in vim: navigate, insert text, save, quit
  • Practice vim search and replace on a test file
  • Make a quick edit with nano for comparison

Next: Redirecting Shell Input and Output