0
0
Bash Scriptingscripting~5 mins

String replacement (${var/old/new}) in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the syntax ${var/old/new} do in bash scripting?
It replaces the first occurrence of the string old with new inside the variable var.
Click to reveal answer
beginner
How do you replace all occurrences of a substring in a variable using bash string replacement?
Use ${var//old/new} with double slashes // to replace all occurrences of old with new.
Click to reveal answer
beginner
Given text="hello world world", what is the result of ${text/world/earth}?
It replaces only the first world with earth, so the result is hello earth world.
Click to reveal answer
beginner
What happens if the substring to replace is not found in the variable?
The variable remains unchanged because there is nothing to replace.
Click to reveal answer
beginner
Can you use string replacement syntax to modify the original variable directly?
No, ${var/old/new} returns the modified string but does not change var unless you assign it back, like var=${var/old/new}.
Click to reveal answer
What does ${var/old/new} do in bash?
AReplaces all occurrences of 'old' with 'new' in 'var'
BDeletes 'old' from 'var'
CReplaces the first occurrence of 'old' with 'new' in 'var'
DAppends 'new' to 'var'
How do you replace all occurrences of 'cat' with 'dog' in variable 'pet'?
A${pet/cat/dog}
B${pet/dog/cat}
C${pet/cat//dog}
D${pet//cat/dog}
If name="banana", what is the result of ${name/na/NA}?
AbaNAna
Bbanana
CbaNANA
DbANAna
What happens if the substring to replace is not found in the variable?
AThe variable becomes empty
BThe variable is unchanged
CAn error is thrown
DThe variable is deleted
How do you update the variable 'text' to replace 'old' with 'new'?
Atext=${text/old/new}
B${text/old/new}
Creplace text old new
Dtext = replace(old,new)
Explain how to replace the first occurrence and all occurrences of a substring in a bash variable using string replacement syntax.
Think about how slashes affect replacement count.
You got /4 concepts.
    Describe what happens if the substring to replace does not exist in the variable when using ${var/old/new}.
    Consider what happens when you try to replace something not present.
    You got /3 concepts.