LFCS Essential Commands Practice Question
A system administrator needs to replace all occurrences of 'oldhost' with 'newhost' in /etc/hosts, but only on lines that contain the string 'domain'. Which sed command accomplishes this?
⚠ Common exam trap
The trap here is that candidates often forget the `g` flag for global replacement, assuming `s` replaces all occurrences by default, or they omit the `-i` flag and think output redirection is sufficient for in-place editing.
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 '/domain/s/oldhost/newhost/g' /etc/hosts
Options A and D are correct because they use `-i` for in-place editing, restrict substitution to lines containing 'domain' with `/domain/`, and use the `g` flag to replace all occurrences on each line. Option B is incorrect because it only outputs lines containing 'domain' to stdout but does not edit the file. Option C is incorrect because it lacks the `g` flag, replacing only the first occurrence per line. Option E is incorrect because `-n` suppresses default output and `p` prints only lines where substitution occurred, but the file is not modified.
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 -i '/domain/s/oldhost/newhost/g' /etc/hosts
Why this is correct
Correct. In-place editing with global replacement on lines containing 'domain'.
- ✗
sed 's/oldhost/newhost/g' /etc/hosts | grep domain
Why it's wrong here
Incorrect. Only outputs matching lines without editing the file.
- ✗
sed -i '/domain/s/oldhost/newhost/' /etc/hosts
Why it's wrong here
Incorrect. Lacks the `g` flag, so only replaces first occurrence per line.
- ✓
sed -i '/domain/s/oldhost/newhost/g' /etc/hosts
Why this is correct
Correct. Same as A, in-place editing with global replacement on lines containing 'domain'.
- ✗
sed -ne '/domain/s/oldhost/newhost/gp' /etc/hosts
Why it's wrong here
Incorrect. Prints modified lines but does not edit the file in-place.
Go deeper
Related to this question
About these practice questions
This LFCS question is part of Courseiva's 507-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 LFCS practice question is part of Courseiva's free Linux Foundation 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 LFCS exam.