0
0
Bash Scriptingscripting~5 mins

String prefix removal (${var#pattern}) in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the syntax ${var#pattern} do in bash scripting?
It removes the shortest matching prefix pattern from the value of the variable var. This means it deletes the smallest part at the start of the string that matches pattern.
Click to reveal answer
intermediate
How is ${var##pattern} different from ${var#pattern}?
${var##pattern} removes the longest matching prefix pattern, while ${var#pattern} removes the shortest matching prefix pattern from the variable's value.
Click to reveal answer
beginner
Example: Given file="/home/user/docs/report.txt", what is the result of ${file#*/}?
It removes the shortest prefix matching */, which is / up to and including the first slash. Result: home/user/docs/report.txt.
Click to reveal answer
beginner
Why use string prefix removal in bash scripts?
It helps to extract parts of strings by cutting off unwanted beginnings, like removing directory paths or prefixes, making scripts cleaner and easier to read.
Click to reveal answer
beginner
What happens if the pattern does not match any prefix in ${var#pattern}?
The variable's value remains unchanged because no matching prefix is found to remove.
Click to reveal answer
What does ${var#*/} do to the string path="/usr/local/bin"?
ARemoves the longest prefix ending with the last slash, resulting in <code>bin</code>
BRemoves the shortest prefix ending with the first slash, resulting in <code>usr/local/bin</code>
CRemoves all slashes from the string
DRemoves the first character only
Which syntax removes the longest matching prefix pattern in bash?
A${var%pattern}
B${var#pattern}
C${var##pattern}
D${var%%pattern}
If var="abc123abc", what is the result of ${var#abc}?
A123abc
Babc123abc
C123
Dbc123abc
What happens if the pattern does not match the start of the string in ${var#pattern}?
AThe pattern is removed from anywhere in the string
BThe entire string is removed
CAn error is thrown
DThe string remains unchanged
Which of these is a practical use of ${var#pattern} in scripts?
AExtracting filename from a full path
BReplacing text inside a string
CRemoving file extensions
DCounting characters in a string
Explain how ${var#pattern} works in bash scripting and give a simple example.
Think about cutting off the start of a string that matches a pattern.
You got /3 concepts.
    Describe the difference between ${var#pattern} and ${var##pattern} and when you might use each.
    One removes the smallest match, the other the biggest match at the start.
    You got /3 concepts.