Bash by Example: Substring Extraction
Extracting parts of a string using offset and length syntax ${var:offset:length} in this sample code.
Code
#!/bin/bash
text="0123456789"
# Syntax: ${variable:offset:length}
# Extract first 3 characters
first_three=${text:0:3}
echo "First 3: $first_three"
# Extract from index 5 to end
from_five=${text:5}
echo "From 5: $from_five"
# Extract 3 characters starting at index 2
middle=${text:2:3}
echo "Middle: $middle"
# Negative offset (from end) requires space or parentheses
last_three=${text: -3}
echo "Last 3: $last_three"Explanation
You can extract substrings in Bash using the parameter expansion syntax ${variable:offset:length}. The offset is the zero-based starting index. This built-in feature is extremely efficient compared to piping to cut or awk.
If length is omitted (e.g., ${variable:offset}), Bash extracts everything from the offset to the end of the string. This is useful for skipping prefixes or processing the tail of a string.
To extract from the end of the string, you can use a negative offset. However, because :- is a separate operator (used for default values), you must put a space before the negative sign (e.g., ${var: -3}) or wrap the offset in parentheses to avoid ambiguity.
Code Breakdown
${text:2:3} starts at index 2 ('2') and takes 3 characters. Result: "234".: -3 (note the space) grabs the last 3 characters. Result: "789".
