BudiBadu Logo
Samplebadu

Bash by Example: Substring Extraction

Bash 5.0+

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

8
Extracts 3 characters starting at index 0. Result: "012".
12
Omitting the length. Extracts from index 5 to the end. Result: "56789".
16
${text:2:3} starts at index 2 ('2') and takes 3 characters. Result: "234".
20
Negative offset. : -3 (note the space) grabs the last 3 characters. Result: "789".