Bird
Raised Fist0
Bash Scriptingscripting~10 mins

String replacement (${var/old/new}) in Bash Scripting - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - String replacement (${var/old/new})
Start with variable var
↓
Check for 'old' substring in var
Yes↓
Replace first occurrence of 'old' with 'new'
↓
Output modified string
↓
End
This flow shows how bash replaces the first occurrence of a substring 'old' with 'new' inside a variable's value.
Execution Sample
Bash Scripting
var="hello world"
new_var=${var/world/universe}
echo "$new_var"
Replace 'world' with 'universe' in the string stored in var and print the result.
Execution Table
StepVariable varOperationResultOutput
1"hello world"Initial value assigned"hello world"
2"hello world"Replace 'world' with 'universe'"hello universe"
3"hello world"Assign to new_var"hello universe"
4"hello world"Print new_var"hello universe"hello universe
5End of script
💡 Script ends after printing the replaced string.
Variable Tracker
VariableStartAfter ReplacementFinal
var"hello world""hello world""hello world"
new_var"hello universe""hello universe"
Key Moments - 2 Insights
Why does only the first occurrence of 'old' get replaced?
Because the syntax ${var/old/new} replaces only the first match. To replace all, you would use ${var//old/new}. See execution_table step 2.
What happens if 'old' is not found in the string?
No replacement occurs, and the original string remains unchanged. This is shown by the initial assignment in step 1 and no change in step 2 if 'old' is missing.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of new_var after step 2?
A"hello world"
B"universe world"
C"hello universe"
D"hello"
💡 Hint
Check the 'Result' column in row for step 2 in execution_table.
At which step is the replaced string printed?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look for the 'Print new_var' operation in execution_table.
If the variable var was "world world", what would new_var be after replacement?
A"universe world"
B"universe universe"
C"world universe"
D"world world"
💡 Hint
Remember ${var/old/new} replaces only the first occurrence, see key_moments explanation.
Concept Snapshot
String replacement in bash uses ${var/old/new} to replace the first occurrence of 'old' with 'new' in var.
To replace all occurrences, use ${var//old/new}.
If 'old' is not found, the string stays the same.
This is useful for quick text changes inside variables.
Full Transcript
This lesson shows how to replace part of a string stored in a variable in bash scripting. We start with a variable var containing a string. Using the syntax ${var/old/new}, bash replaces the first occurrence of the substring 'old' with 'new'. The replaced string is then stored in a new variable or used directly. We traced the steps: assigning the initial string, performing the replacement, assigning the result, and printing it. We also clarified that only the first match is replaced unless you use double slashes. If the substring is not found, the string remains unchanged. This helps beginners understand how to manipulate strings easily in bash scripts.

Practice

(1/5)
1. What does the expression ${var/old/new} do in bash scripting?
easy
A. Appends 'new' to the variable 'var' if it contains 'old'.
B. Replaces the first occurrence of 'old' with 'new' in the variable 'var'.
C. Deletes the variable 'var' if it contains 'old'.
D. Replaces all occurrences of 'old' with 'new' in the variable 'var'.

Solution

  1. Step 1: Understand the syntax ${var/old/new}

    This syntax replaces only the first occurrence of the substring 'old' with 'new' inside the variable 'var'.
  2. Step 2: Differentiate from ${var//old/new}

    The double slash version replaces all occurrences, but the single slash replaces only the first one.
  3. Final Answer:

    Replaces the first occurrence of 'old' with 'new' in the variable 'var'. -> Option B
  4. Quick Check:

    Single slash means first occurrence only [OK]
Hint: Single slash replaces first match only, double slash replaces all [OK]
Common Mistakes:
  • Confusing single slash with double slash for all replacements
  • Thinking it deletes or appends instead of replacing
  • Assuming it works on strings outside variables
2. Which of the following is the correct syntax to replace the first occurrence of 'cat' with 'dog' in variable animal?
easy
A. ${animal/cat/dog}
B. ${animal//cat/dog}
C. ${animal/cat|dog}
D. ${animal:cat:dog}

Solution

  1. Step 1: Identify correct replacement syntax

    The correct syntax for replacing the first occurrence is ${variable/old/new}, so ${animal/cat/dog} is correct.
  2. Step 2: Check other options for errors

    ${animal//cat/dog} uses double slash which replaces all occurrences, not just the first. Options C and D use invalid syntax.
  3. Final Answer:

    ${animal/cat/dog} -> Option A
  4. Quick Check:

    Single slash correct for first occurrence [OK]
Hint: Use single slash for first replacement, double slash for all [OK]
Common Mistakes:
  • Using double slash when only first replacement is needed
  • Using wrong delimiters like | or : instead of /
  • Confusing syntax with substring extraction
3. Given text="hello world world", what is the output of echo ${text/world/earth}?
medium
A. hello earth earth
B. hello world earth
C. hello earth world
D. hello world world

Solution

  1. Step 1: Understand the variable content

    The variable text contains "hello world world" with two 'world' words.
  2. Step 2: Apply ${text/world/earth}

    This replaces only the first occurrence of 'world' with 'earth', so the result is "hello earth world".
  3. Final Answer:

    hello earth world -> Option C
  4. Quick Check:

    Single slash replaces first match only [OK]
Hint: Single slash replaces only first match, so second 'world' stays [OK]
Common Mistakes:
  • Expecting all 'world' to change to 'earth'
  • Confusing output with original variable
  • Misreading variable content
4. What is wrong with this code snippet?
file="data.txt"
newfile=${file/data/txt}
echo $newfile
medium
A. It replaces 'data' with 'txt' correctly.
B. Syntax error due to missing slashes in replacement.
C. It replaces 'data' with 'txt' but misses the dot.
D. It replaces 'data' with 'txt' but changes the file extension incorrectly.

Solution

  1. Step 1: Check the replacement syntax

    The replacement syntax must be ${var/old/new} with slashes separating parts. Here, ${file/data/txt} is correct syntax.
  2. Step 2: Analyze the replacement effect

    The code replaces 'data' with 'txt', so 'data.txt' becomes 'txt.txt'. There is no syntax error.
  3. Step 3: Identify the logical issue

    While the code executes correctly, the replacement of 'data' with 'txt' produces 'txt.txt', which alters the filename in a way that incorrectly impacts the intended file extension handling.
  4. Final Answer:

    It replaces 'data' with 'txt' but changes the file extension incorrectly. -> Option D
  5. Quick Check:

    Replacement changes 'data' to 'txt', affecting filename [OK]
Hint: Check slashes and replaced parts carefully for syntax and effect [OK]
Common Mistakes:
  • Assuming syntax error when slashes are correct
  • Ignoring that replacement changes filename parts
  • Confusing replacement with substring extraction
5. 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
A. Use parameter expansion with substring and manual replacement.
B. Use ${sentence//apple/orange} to replace all.
C. Use ${sentence/apple/orange} twice.
D. Use ${sentence/apple/orange} once; it replaces second occurrence automatically.

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]
Hint: Single slash replaces first only; second needs manual substring handling [OK]
Common 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
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard