Bird
0
0

How can you use sed to replace only the second occurrence of 'cat' with 'dog' on each line?

hard🚀 Application Q9 of 15
Bash Scripting - Text Processing in Scripts
How can you use sed to replace only the second occurrence of 'cat' with 'dog' on each line?
Ased 's/cat/dog/g2' file.txt
Bsed '2s/cat/dog/' file.txt
Csed 's/cat/dog/2' file.txt
Dsed 's/cat/dog/1g' file.txt
Step-by-Step Solution
Solution:
  1. Step 1: Understand occurrence flag in sed substitution

    Adding a number after the substitution command replaces only that occurrence number per line.
  2. Step 2: Identify correct syntax for second occurrence

    sed 's/cat/dog/2' file.txt uses 's/cat/dog/2' which replaces only the second 'cat' per line.
  3. Final Answer:

    sed 's/cat/dog/2' file.txt -> Option C
  4. Quick Check:

    Number after 's///' targets specific occurrence [OK]
Quick Trick: Use number after 's///' to replace nth occurrence only [OK]
Common Mistakes:
MISTAKES
  • Using 'g2' which is invalid
  • Confusing line number with occurrence number
  • Assuming '2s' targets second occurrence

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes