Create and Edit
Text Files

Create and edit text files

CIS126RH | RHEL System Administration 1
Mesa Community College

Nearly every configuration task on a RHEL system involves editing a plain text file. The ability to create, view, and modify text files from the command line — without a graphical application — is a foundational skill for every Linux administrator. This module covers the tools and techniques used daily in production environments and tested on the RHCSA exam.

Learning Objectives

  1. Create text files without an editor — Use touch, echo, redirection, and here documents to create and populate files from the command line
  2. View file contents — Use cat, less, head, and tail to read files efficiently
  3. Navigate and edit files with vim — Move between modes, navigate the file, make changes, and save or quit
  4. Use vim efficiently — Apply search, find-and-replace, line numbers, and undo to edit files accurately and quickly

Creating Files Without an Editor

These techniques create or populate files entirely from the command line — essential for scripts and quick tasks.

touch — Create an Empty File

# Create an empty file, or update timestamps if it exists
$ touch notes.txt
$ touch file1.txt file2.txt file3.txt

echo and Redirection — Write Content

# Write a single line — overwrites the file
$ echo 'PasswordAuthentication no' > setting.txt

# Append a line without overwriting
$ echo 'AllowUsers student admin' >> setting.txt

# Write a line to a root-owned file using sudo tee
$ echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
Greater-than overwrites

> replaces the entire file. Use >> to add to an existing file without destroying its contents.

Here Documents for Multi-Line Files

A here document writes multiple lines into a file in one command — no editor required.

# Write a multi-line file with cat and a here document
$ cat <<EOF > /tmp/hosts-entry.txt
192.168.1.10  servera servera.lab.example.com
192.168.1.11  serverb serverb.lab.example.com
EOF

# Append to a root-owned file using sudo tee
$ sudo tee -a /etc/hosts <<EOF
192.168.1.10  servera servera.lab.example.com
192.168.1.11  serverb serverb.lab.example.com
EOF

# Write a simple shell script without opening an editor
$ cat <<EOF > /usr/local/bin/hello.sh
#!/bin/bash
echo "Hello from $(hostname)"
EOF
EOF is just a convention

The delimiter word can be anything — EOF, END, DONE. The closing delimiter must appear alone on its own line with no leading spaces.

Viewing File Contents

Choose the right viewing tool based on the file size and what you need to see.

Command Best for Key options
cat Small files — prints everything at once -n number lines, -A show hidden characters
less Large files — scroll up and down interactively /pattern search, q quit, G jump to end
head First lines of a file -n 20 show 20 lines (default is 10)
tail Last lines of a file; following a live log -n 20 last 20 lines, -f follow in real time
# Show line numbers with cat
$ cat -n /etc/ssh/sshd_config

# Last 20 lines then follow new entries as they are written
$ tail -n 20 -f /var/log/messages

Introduction to vim

vimVi IMproved — is the standard text editor for RHEL system administration. It is always available, even in minimal and rescue environments.

  • Available on every RHEL system, including minimal installs and single-user mode
  • Works over SSH without any graphical interface
  • Required for the RHCSA exam — no graphical editor is guaranteed to be present
  • Fast and efficient once the key bindings become muscle memory

Opening vim

# Open an existing file to edit
$ vim /etc/ssh/sshd_config

# Create and open a new file
$ vim newfile.txt

# Open a file and jump to line 42
$ vim +42 /etc/ssh/sshd_config
RHCSA Requirement

The RHCSA exam requires you to edit configuration files. vim is the only editor guaranteed to be installed. You must be able to open, edit, save, and quit without assistance.

vim Modes

vim is a modal editor — the same key does different things depending on which mode is active. Understanding modes is the key to understanding vim.

Mode What you can do How to enter it
Normal Navigate, delete, copy, paste, issue commands — the default mode Press Esc from any other mode
Insert Type text — keys insert characters as in a regular editor Press i, a, o, or O in Normal mode
Visual Select a block of text to copy, cut, or replace Press v (character), V (line), or Ctrl+v (block)
Command Run ex commands — save, quit, search-and-replace, set options Press : in Normal mode
When in doubt, press Escape

Pressing Esc always returns you to Normal mode from any other mode. If you are unsure what mode you are in, press Esc once or twice and you will be back in Normal mode.

Entering Insert Mode

There are several keys that enter Insert mode, each starting the cursor in a different position. All are used in Normal mode.

Key Inserts text…
iBefore the cursor — the most common entry point
IAt the beginning of the current line
aAfter the cursor
AAt the end of the current line
oOn a new line below the current line
OOn a new line above the current line
Most useful insert keys

i — insert before cursor (most common)
A — append at end of line (add to end of a config line)
o — open new line below (add a new setting below the current one)

Navigating in Normal Mode

Press Esc to return to Normal mode. All navigation happens here.

Key or command Movement
h j k lLeft, down, up, right — one character or line
Arrow keysSame as h j k l — work in most terminals
w / bForward one word / back one word
0 / $Beginning of line / end of line
ggJump to the first line of the file
GJump to the last line of the file
42G or :42Jump to line 42
Ctrl+fScroll one screen forward (page down)
Ctrl+bScroll one screen backward (page up)

Saving and Quitting

All save and quit commands are entered in Command mode — press : from Normal mode to open the command prompt at the bottom of the screen.

Command Action
:wWrite (save) the file — stay in vim
:qQuit — only works if there are no unsaved changes
:wqWrite and quit — save then exit
:xWrite and quit — same as :wq
ZZWrite and quit — Normal mode shortcut, no colon needed
:q!Quit without saving — discard all changes
:w filenameWrite to a different filename — save a copy
:wq!Force write and quit — override read-only warning
The two most important commands

:wq — save and exit after making changes.
:q! — exit without saving if you made a mistake and want to start over.

Deleting and Changing Text

All of these work in Normal mode — no need to enter Insert mode first.

Key Action
xDelete the character under the cursor
dwDelete from cursor to the end of the current word
ddDelete the entire current line
5ddDelete 5 lines starting from the current line
DDelete from cursor to the end of the line
cwDelete current word and enter Insert mode
ccDelete current line and enter Insert mode
rReplace the character under the cursor with the next key pressed
uUndo the last change
Ctrl+rRedo — reverse the last undo
Undo is unlimited

Press u repeatedly to undo multiple changes. vim keeps a full undo history for the current session — you can always get back to the original file contents.

Copying and Pasting

vim uses the term yank for copy and put for paste.

Key Action
yyYank (copy) the current line
3yyYank 3 lines starting from the current line
ywYank from cursor to end of word
y$Yank from cursor to end of line
pPut (paste) after the cursor or below the current line
PPut before the cursor or above the current line
dd then pCut and paste — move a line

Visual Mode Selection

Press V to select whole lines, move to select a range,
then press y to yank or d to delete the selection.
Duplicate a line

yy then p duplicates the current line immediately below it — useful when adding a similar config option that differs only slightly from an existing one.

Searching in vim

vim's search works in Normal mode and uses regular expressions.

Command Action
/patternSearch forward from cursor for pattern
?patternSearch backward from cursor for pattern
nJump to the next match in the same direction
NJump to the next match in the opposite direction
:nohClear search highlighting
*Search forward for the word under the cursor
#Search backward for the word under the cursor
# Find PasswordAuthentication in the current file
/PasswordAuthentication

# Enable line numbers to help orient yourself
:set number

# Jump directly to line 100
:100
Highlight all matches

Run :set hlsearch to highlight every occurrence of the search pattern. Run :noh to clear the highlighting when done.

Find and Replace

vim's substitute command follows the pattern :s/find/replace/flags. It accepts regular expressions for the find and replace terms.

Command What it does
:s/old/new/Replace first occurrence on the current line
:s/old/new/gReplace all occurrences on the current line
:%s/old/new/gReplace all occurrences in the entire file
:%s/old/new/giReplace all occurrences, case-insensitive
:%s/old/new/gcReplace all, asking for confirmation each time
:10,20s/old/new/gReplace all occurrences between lines 10 and 20
# Change 'yes' to 'no' for PasswordAuthentication — whole file
:%s/PasswordAuthentication yes/PasswordAuthentication no/g

# Uncomment all lines that start with # Port
:%s/^# Port/Port/
RHCSA Focus

:%s/old/new/g is one of the most useful commands for quickly changing a setting across an entire configuration file. Know this pattern for the exam.

Useful vim Settings

These settings can be entered in Command mode during a session or saved in ~/.vimrc to apply every time vim opens.

Command Effect
:set numberShow line numbers
:set nonumberHide line numbers
:set hlsearchHighlight all search matches
:set ignorecaseCase-insensitive search
:set autoindentAuto-indent new lines to match the previous line
:set expandtabInsert spaces instead of tab characters
:set tabstop=4Set tab width to 4 spaces
:syntax onEnable syntax highlighting

Minimal ~/.vimrc for System Administration

set number
set hlsearch
set ignorecase
set autoindent
syntax on

vim in Real Admin Tasks

Edit a Config File

$ sudo vim /etc/ssh/sshd_config
  /PasswordAuthentication    <-- jump to the setting
  A                          <-- move to end of line, insert mode
  change yes to no           <-- edit the value
  Esc :wq                    <-- save and quit

Comment Out a Line

  /^Port                     <-- find the Port line
  I                          <-- insert at start of line
  #                          <-- type the comment character
  Esc :wq

Add Multiple Lines at the End

  G                          <-- jump to last line
  o                          <-- open new line below
  type new content           <-- add lines
  Esc :wq
Pre-edit habit

Before editing any critical file, back it up: sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
If something goes wrong, :q! discards changes, or restore from the backup.

Knowledge Check

Answer these before moving to the next slide.

  1. You are in vim and have made several changes. The file looks wrong. What command exits vim and discards all your changes?
  2. You want to add a new line of text below line 42 in a config file. Which key jumps to line 42, and which key opens a new line below it?
  3. What is the vim command to replace every occurrence of the word yes with no throughout the entire file?
  4. You need to write two lines into /etc/hosts without opening vim. Write the command using a here document and sudo tee.
  5. What is the difference between cat and less for viewing a large file?
  6. You open vim and start typing, but your keystrokes are triggering commands instead of appearing as text. What happened, and how do you fix it?

Knowledge Check — Answers

  1. Press Esc to ensure you are in Normal mode, then type :q! and press Enter. This quits without saving — all changes are discarded.
  2. Type :42 and press Enter to jump to line 42. Press o to open a new blank line below it and enter Insert mode.
  3. :%s/yes/no/g — the percent sign applies the substitution to every line in the file; the g flag replaces all occurrences per line.
  4. $ sudo tee -a /etc/hosts <<EOF
    192.168.1.10  servera servera.lab.example.com
    192.168.1.11  serverb serverb.lab.example.com
    EOF
  5. cat dumps the entire file to the screen at once — impractical for large files. less opens an interactive pager that lets you scroll up and down, search with /, and quit with q without printing the whole file to the terminal.
  6. You are in Normal mode, not Insert mode. Keystrokes in Normal mode trigger vim commands rather than typing text. Press i to enter Insert mode — you will see -- INSERT -- at the bottom of the screen.

Key Takeaways

  1. Files can be created without opening an editor. Use touch for empty files, echo >> for single lines, and here documents with cat or sudo tee for multi-line content. These techniques are essential for scripts and exam tasks.
  2. vim is a modal editor — modes are everything. Normal mode is the default. Press i to insert text. Press Esc to return to Normal mode from anywhere. When in doubt, press Esc.
  3. The two essential exit commands are :wq and :q! Save and quit with :wq. Discard all changes and quit with :q!. Back up critical files before editing — cp file file.bak — so :q! is not your only safety net.
  4. Search and substitute are faster than scrolling. Use /pattern to jump to a setting instantly. Use :%s/old/new/g to change a value across the entire file. Use :set number to show line numbers whenever an error message references a specific line.

Graded Lab

  • Use touch to create three empty files named file1.txt, file2.txt, and file3.txt
  • Use echo with redirection to write one line into file1.txt and append a second line — confirm both lines are present with cat
  • Use a here document with sudo tee to append two host entries to /tmp/hosts-test (do not modify the real /etc/hosts)
  • Open /etc/ssh/sshd_config in vim — use :set number to enable line numbers, search for PasswordAuthentication, and navigate to that line without using arrow keys
  • In vim, copy the PasswordAuthentication line with yy, paste it below with p, then change the value in the copy — quit without saving with :q!
  • Use :%s to replace every occurrence of a word in a test file, then save and quit with :wq
RHCSA Objective

"Create and edit text files." Every configuration task on the exam requires editing a text file. vim fluency directly determines your speed and accuracy across the entire exam.