CertNote/ Commute Study Notes
Roadmap
KOEN
CLF-C02 · FoundationalCloud Practitioner - Foundational
DVA-C02 · AssociateDeveloper - Associate
SAA-C03 · AssociateSolutions Architect - Associate
SOA-C02 · AssociateCloudOps Engineer - Associate
SAP-C02 · ProfessionalSolutions Architect - Professional
DOP-C02 · ProfessionalDevOps Engineer - Professional
Linux Master 2 · 2급KAIT Linux Master - Level 2
  • Week 1
    • 1.Operating Systems and the Kernel: What Linux Does
    • 2.The Birth of Linux: From Unix to Linus
    • 3.Free Software and Open Source: What a License Decides
    • 4.Distributions: The Unit That Bundles the Kernel and Tools for Sale
    • 5.Week 1 Review: The Identity Behind the Name Linux
  • Week 2
  • Week 3
  • Week 4
  • Week 5
  • Week 6
    • 1.The Three Modes of the vi Editor
    • 2.vi Search and Replace, and Other Editors
    • 3.Process Concepts and Types
    • 4.Process Commands and Job Scheduling
    • 5.Week 6 Comprehensive Review: Editors and Processes
  • Week 7
  • Week 8
  • Week 9
  • Week 10
  • Week 11
SCS-C03 · SpecialtySecurity - Specialty
Linux Master 1 · 1급KAIT Linux Master - Level 1
MLA-C01 · AssociateMachine Learning Engineer - Associate
AIF-C01 · FoundationalAI Practitioner - Foundational
DEA-C01 · AssociateData Engineer - Associate
MLS-C01 · SpecialtyMachine Learning - Specialty
SQLD · 개발자SQL Developer (SQLD)

© CertNote · 주간랩스

  • About
  • Changelog
  • Contact
  • Terms
  • Privacy
← Linux Master 2/Week 6/Day 2

Based on the Linux Master 2 exam syllabus·Report an error

Linux Master 2· AssociateWeek 6 · Day 2~20 min read

Day 2 - vi Search and Replace, and Other Editors

📌 Key Points

  • Search with /pattern (downward) and ?pattern (upward); the next result is n and the opposite direction is N.
  • The basic form of substitution is :s/find/replace/.
  • % means the whole file, and g means everything within a line. :%s/A/B/g is the classic form.
  • vi settings are stored in ~/.vimrc (personal) and /etc/vimrc (global).
  • nano shows its shortcut keys at the bottom of the screen, and emacs has no modes. Only vi has modes.

Search

CommandDirection
/patternSearch downward from the cursor
?patternSearch upward from the cursor
nNext result in the same direction
NNext result in the opposite direction
   /error        search downward for error
   ?error        search upward for error
   n             next result
   N             next result in the opposite direction
  • A search starts in command mode. When you press /, an input line appears at the bottom of the screen.
  • The relationship between n and N is an exam point. N is not "upward"; it is the opposite of the direction you first searched. If you searched with ?, N goes downward.
How the search was first madeWhere n goesWhere N goes
/patternDownUp
?patternUpDown

Symbols Used in Patterns

SearchWhat it finds
/^rootLines that start with root
/bash$Lines that end with bash
/a.cAny single character between a and c — abc, a1c
/\<the\>The word the only (excludes there, other)
/\/etc\/hostsA string containing slashes — write it as \/
  • Since / itself is the "start search" symbol, if the string you are looking for contains a slash, put a backslash in front.
  • The search does not stop at the end. It wraps around to the beginning and keeps looking, and the bottom line shows search hit BOTTOM, continuing at TOP.
  • If nothing is found, E486: Pattern not found: pattern appears.
  • To ignore case, use :set ic, and to temporarily turn off search highlighting use :noh (vim).

Substitution

   :  %  s / Seoul / Busan / g
   │  │  │    │        │     │
   │  │  │    │        │     └── g  everything on the line
   │  │  │    │        └──────── replacement string
   │  │  │    └───────────────── string to find
   │  │  └────────────────────── s  substitute
   │  └───────────────────────── %  the whole file
   └──────────────────────────── :  ex mode
CommandRange
:s/A/B/Only the first A on the line with the cursor
:s/A/B/gAll A's on the line with the cursor
:%s/A/B/gAll A's in the whole file
:1,10s/A/B/gAll A's on lines 1 through 10
:%s/A/B/gcReplace throughout but confirm each one (confirm)

Tell % and g apart. % decides up to which lines, and g decides how many within one line. :%s/A/B/g, with both attached, means "replace everything in the whole file."

Before and After Replacing

This is the result of using each of four commands on the same two lines, with the cursor on line 1.

   Original        1  banana apple          2  grape banana
 
   :s/a/A/         1  bAnana apple          2  grape banana      only the first on the current line
   :s/a/A/g        1  bAnAnA Apple          2  grape banana      all on the current line
   :%s/a/A/        1  bAnana apple          2  grApe banana      only the first on every line
   :%s/a/A/g       1  bAnAnA Apple          2  grApe bAnAnA      all on every line
  • The third row is the trap. With only %, just "one per line" is changed. The banana on line 2 stayed as it was.

How to Write a Range

RangeTarget
(omitted)The line with the cursor
%The whole file — same as 1,$
1,10Lines 1 through 10
.,$From the current line to the last line
10,$From line 10 to the last line
.,+5The current line and the five lines below it
  • In a range, . is the current line and $ is the last line. % is shorthand for 1,$.
  • Ranges are used not only for substitution but for other ex commands too — :1,5d deletes lines 1 through 5.

Commonly Used Substitution Forms

CommandWhat it does
:%s/A//gDelete all A (leave the replacement empty)
:%s/^/#/Add # to the start of every line — comment out everything at once
:%s/^#//Remove the # at the start of lines
:%s/A/B/giReplace ignoring case
:%s#/usr/local#/opt#gUse # as the delimiter — when replacing paths with many slashes
:g/pattern/dDelete entire lines containing that pattern
  • The delimiter does not have to be /. The character right after s becomes the delimiter.
  • If you add c, it asks replace with B (y/n/a/q/l/^E/^Y)? at each match. y replace, n skip, a all the rest, q stop.
  • If you replaced wrongly, undo it in command mode with u. One whole substitution is undone at once.
  • The g at the end (an option) and the :g at the start (a command) are different things. The option g means "everything in a line," and the command :g means "run the following command on every line that has the pattern."

Commonly Used Settings

CommandWhat it does
:set nuShow line numbers
:set nonuHide line numbers
:set aiAuto-indent (autoindent)
:set ts=4Set tab size (tabstop)
:set icIgnore case when searching (ignorecase)
:set hlsearchHighlight search results
:set sw=4Auto-indent width (shiftwidth)
:set smShow matching brackets (showmatch)
:set listShow invisible characters, such as tabs (^I) and line ends ($)
:set allView the current values of all options
:syntax onTurn on syntax highlighting (vim)
AbbreviationFull nameAbbreviationFull name
nunumberaiautoindent
icignorecasetstabstop
swshiftwidthsmshowmatch
  • To turn one off, put no in front — nonu, noai, noic, nolist. It is not that each option has its own separate off command.

  • Options that take a value are given with = — ts=4. The form differs from on/off options.

  • If you want to know the current value, add a question mark. :set ts? answers like tabstop=8 (the default is 8).

  • Settings given this way disappear when you close the editor.

  • To keep using them, write them in a configuration file.

FileScope
~/.vimrcPersonal settings
/etc/vimrcGlobal settings (all users)
~/.exrcPersonal settings file of the old vi
   " ~/.vimrc example
   set nu
   set ai
   set ts=4
  • It is the same structure as the shell's .bashrc. If it starts with ~/ it is personal; if /etc/ it is global.
  • Inside a configuration file, it is usual to write set nu without a colon. Comments start with a double quote ("), unlike the shell's #.
  • The global file is read first and then overridden by the personal file. The location of the global file varies by distribution: /etc/vimrc on the Red Hat family and /etc/vim/vimrc on the Debian family.
Easily confused fileActual role
~/.vimrcSettings you write yourself
~/.viminfoA record vim leaves automatically — search terms, command history, copied content. It is not a configuration file
~/.exrcThe configuration file of the original vi and ex. vim reads this only when ~/.vimrc does not exist
.filename.swpA swap file created during editing. Used for recovery after an abnormal exit

Other Editors

nano

   ^G Get Help    ^O Write Out    ^X Exit
   └ ^ means the Ctrl key
ShortcutWhat it does
Ctrl+OSave (Write Out)
Ctrl+XExit (Exit)
Ctrl+WSearch
Ctrl+KCut one line
Ctrl+GHelp
  • There are no modes. When you open it, you can start typing right away.
  • A list of shortcuts is always visible at the bottom of the screen. That is why it is easy for beginners.
  • It is an improved version of pico and was made by the GNU project.
ShortcutWhat it does
Ctrl+UPaste the cut line
Ctrl+RRead in the contents of another file
Ctrl+\Replace a string
Ctrl+CShow the current cursor position
   Ctrl+X
   Save modified buffer?   Y Yes   N No   ^C Cancel     ← Y
   File Name to Write: memo.txt                         ← Enter
  • If you press Ctrl+X after editing, it asks whether to save. After Y, you confirm the file name and press Enter, and it saves and exits. It does not hold out with just a warning, as vi does.
  • In the list at the bottom of the screen, ^ is the Ctrl key and M- is the Alt (Meta) key.
  • pico was originally an editor bundled with the mail program Pine. nano is its remake as free software.

emacs

ShortcutWhat it does
Ctrl+X Ctrl+SSave
Ctrl+X Ctrl+CExit
Ctrl+GCancel a command
  • It was created by Richard Stallman. It is the editor of the GNU project.
  • It has no modes; instead it invokes every feature with Ctrl and Meta (Alt) key combinations.
  • Its features can be extended in Lisp, so it is called an environment that goes beyond an editor.
ShortcutWhat it does
Ctrl+X Ctrl+FOpen a file (find file)
Ctrl+S / Ctrl+RSearch downward / upward
Ctrl+KCut from the cursor to the end of the line (kill)
Ctrl+YPaste (yank)
Ctrl+A / Ctrl+EStart / end of the line
Ctrl+X uUndo
  • Ctrl+X Ctrl+S means holding Ctrl while pressing x, then s. The emacs documentation writes this as C-x C-s. C- is Ctrl and M- is Meta (Alt).
  • Both saving and exiting start with Ctrl+X and differ only in the following letter — with Ctrl+S it is save, with Ctrl+C it is exit.
  • The meaning of yank is the opposite of vi. vi's yy is copy, while emacs's Ctrl+Y is paste.
  • The Ctrl+A, Ctrl+E, Ctrl+K, and Ctrl+R on the bash command line are exactly emacs-style shortcuts. The keys we used last week come from here.
  • emacs runs on the console and also in a graphical window under X Window.

Comparing the Three Editors

Categoryvi / vimemacsnano
CreatorBill JoyRichard StallmanGNU (pico improvement)
ModesYes (3)NoneNone
Save:wCtrl+X Ctrl+SCtrl+O
Exit:qCtrl+X Ctrl+CCtrl+X
Configuration file~/.vimrc~/.emacs~/.nanorc
CharacterAvailable everywhereHighly extensibleEasy to learn

The answer to "Which editor has modes?" is vi. emacs and nano have no modes.

The Same Task in Three Editors

What you want to dovi / vimemacsnano
Save and quit:wqCtrl+X Ctrl+S then Ctrl+X Ctrl+CCtrl+X then Y, Enter
Quit without saving:q!Ctrl+X Ctrl+C then answer no to savingCtrl+X then N
Search/patternCtrl+SCtrl+W
Cut one lineddCtrl+K (cursor to end of line)Ctrl+K
PastepCtrl+YCtrl+U
  • If the shortcut is a Ctrl combination it is emacs or nano; if it is a colon or a single letter it is vi. When they are mixed in the choices, split them by this criterion first.
  • If it ends with a single Ctrl+X it is nano; if it takes Ctrl+X Ctrl+C twice it is emacs. The exit keys are similar, so questions swap them.
  • Ctrl+K is cut in both editors, but pasting differs: Ctrl+Y in emacs and Ctrl+U in nano.

Tomorrow we cover running programs: the concept and types of processes.

📖 Glossary

  • /pattern : The vi command that searches for a string downward from the cursor.
  • n / N : Keys that move through search results in the same direction / the opposite direction.
  • Substitute : The ex command that replaces strings in the form :s/A/B/.
  • % : A range symbol that makes the whole file the target of a substitution.
  • g : An option that makes a substitution replace every match within a line.
  • ~/.vimrc : vim's personal configuration file. The global configuration is /etc/vimrc.
  • nano : A GNU editor that improves on pico. It has no modes and shows shortcuts at the bottom of the screen.
  • emacs : A highly extensible editor created by Richard Stallman. It is operated with key combinations rather than modes.

📝 Practice Questions

Click a choice to reveal the answer and explanation.

Question 1

Which of the following vi commands replaces every apple in the whole file with orange?

Question 2

Which of the following vi commands displays line numbers on the screen?

Question 3

Which of the following is the file that stores vim's personal environment settings?

Question 4

Which of the following editors has no distinct editing modes, so you can type characters immediately after launching it?

Question 5

Which of the following is the shortcut that saves what you have written in the nano editor?

PreviousThe Three Modes of the vi EditorWeek 6 · Day 1Next Process Concepts and TypesWeek 6 · Day 3

Official references

  • Linux Master 2 official exam syllabus(opens in a new tab)

On this page

  • Key Points
  • Search
  • Symbols Used in Patterns
  • Substitution
  • Before and After Replacing
  • How to Write a Range
  • Commonly Used Substitution Forms
  • Commonly Used Settings
  • Other Editors
  • nano
  • emacs
  • Comparing the Three Editors
  • The Same Task in Three Editors
  • Glossary
  • Practice Questions