LPIC-1 Shells, Scripting and Data Management Practice Question
An administrator needs to replace all occurrences of 'old_host' with 'new_host' in the file /etc/hosts. Which sed command should be used?
⚠ Common exam trap
The trap here is that candidates often forget the `g` flag for global replacement or omit the `-i` flag for in-place editing, mistakenly thinking sed modifies files by default.
Answer choices
Why each option matters
Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.
Correct answer & explanation
✓
sed -i 's/old_host/new_host/g' /etc/hosts
The `-i` flag enables in-place editing of the file, and the `g` flag (global) ensures all occurrences on each line are replaced, not just the first. The command `sed -i 's/old_host/new_host/g' /etc/hosts` modifies the file directly, replacing every instance of 'old_host' with 'new_host' throughout the file.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✗
sed -n 's/old_host/new_host/gp' /etc/hosts
Why it's wrong here
Prints only replaced lines but does not edit the file.
- ✗
sed -i 's/old_host/new_host/' /etc/hosts
Why it's wrong here
Without the g flag, sed replaces only the first occurrence per line, leaving later old_host entries unchanged. It is tempting because -i edits in place, which the task needs, and would be correct if only the first match on each line required replacement.
- ✓
sed -i 's/old_host/new_host/g' /etc/hosts
Why this is correct
The `-i` flag edits /etc/hosts in place, satisfying the requirement to replace all occurrences without redirecting to a temporary file. The `g` suffix applies the substitution globally across every match on each line, not merely the first, so multiple instances of 'old_host' are all rewritten to 'new_host'.
- ✗
sed 's/old_host/new_host/g' /etc/hosts
Why it's wrong here
Omitting -i sends the substituted text to standard output, leaving /etc/hosts untouched; the administrator needs the file rewritten. It is tempting because the s///g expression is otherwise correct, and would be right for piping results or testing the pattern before editing.
Go deeper
Related to this question
About these practice questions
This LPIC-1 question is part of Courseiva's 402-question bank — original exam-style content with full explanations and wrong-answer analysis, never real exam questions or exam dumps. Learn why practice questions differ from exam dumps →
JA
Written by Johnson Ajibi, MSc IT Security
Senior Network & Security Engineer · founder of Courseiva
This LPIC-1 practice question is part of Courseiva's free LPI certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the LPIC-1 exam.