Bird
0
0

You have a variable sentence="apple banana apple cherry apple". How do you replace only the second occurrence of 'apple' with 'orange' using bash string replacement?

hard🚀 Application Q15 of 15
Bash Scripting - String Operations
You have a variable sentence="apple banana apple cherry apple". How do you replace only the second occurrence of 'apple' with 'orange' using bash string replacement?
AUse parameter expansion with substring and manual replacement.
BUse <code>${sentence//apple/orange}</code> to replace all.
CUse <code>${sentence/apple/orange}</code> twice.
DUse <code>${sentence/apple/orange}</code> once; it replaces second occurrence automatically.
Step-by-Step Solution
Solution:
  1. Step 1: Understand limitation of ${var/old/new}

    This syntax replaces only the first occurrence, no direct way to replace the second occurrence.
  2. Step 2: Consider manual approach

    To replace the second occurrence, you must split or manipulate the string manually using substring extraction and concatenation.
  3. Step 3: Confirm the approach

    Bash parameter expansion with single or double slashes cannot target specific non-first occurrences; manual string manipulation using substrings is required.
  4. Final Answer:

    Use parameter expansion with substring and manual replacement. -> Option A
  5. Quick Check:

    Only manual substring methods can target second occurrence [OK]
Quick Trick: Single slash replaces first only; second needs manual substring handling [OK]
Common Mistakes:
MISTAKES
  • Assuming single replacement syntax can target second occurrence
  • Using double slash to replace all instead of just second
  • Expecting repeated use of ${var/old/new} to replace second occurrence

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes