0
0
Bash Scriptingscripting~5 mins

Substring extraction (${var:offset:length}) in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the syntax ${var:offset:length} do in bash scripting?
It extracts a substring from the variable var, starting at position offset and taking length characters.
Click to reveal answer
beginner
If var="hello world", what is the result of ${var:6:5}?
The substring starting at position 6 with length 5 is world.
Click to reveal answer
intermediate
What happens if the length in ${var:offset:length} is omitted?
The substring will include all characters from offset to the end of the string.
Click to reveal answer
intermediate
Can the offset be negative in ${var:offset:length}? What does it mean?
Yes, a negative offset counts from the end of the string backwards. For example, ${var: -3} starts 3 characters from the end.
Click to reveal answer
beginner
How would you extract the first 4 characters of a variable var in bash?
Use ${var:0:4} to get the first 4 characters starting at position 0.
Click to reveal answer
What does ${var:3:2} extract from var="abcdefg"?
A"ef"
B"cd"
C"de"
D"bc"
If var="hello", what does ${var:1} return?
A"h"
B"he"
C"o"
D"ello"
What happens if offset is negative in ${var:offset:length}?
ACounts from start of string
BCounts from end of string backwards
CCauses an error
DReturns empty string
Which command extracts the first 3 characters of var?
A${var:0:3}
B${var:3:0}
C${var:3:3}
D${var:1:3}
If var="bash scripting", what does ${var:5} return?
A"scripting"
B"bash scripting"
C"script"
D"bash"
Explain how to extract a substring from a bash variable using the syntax ${var:offset:length}. Include what happens if length is omitted or offset is negative.
Think about how you cut a piece from a string, starting point and size.
You got /5 concepts.
    Describe a real-life example where substring extraction in bash scripting can be useful.
    Imagine you have a filename and want just the extension.
    You got /4 concepts.