0
0
Bash Scriptingscripting~5 mins

Substring extraction (${var:offset:length}) in Bash Scripting

Choose your learning style9 modes available
Introduction
You use substring extraction to get a part of a text stored in a variable. It helps you pick only the piece you need.
You want to get the first few letters of a filename to check its type.
You need to extract a date from a longer string like '2024-06-15_report.txt'.
You want to get a user ID from a string that contains extra info.
You want to shorten a long message by taking only the first 10 characters.
Syntax
Bash Scripting
${variable:offset:length}
Offset starts at 0, meaning the first character is at position 0.
Length is optional. If you leave it out, it takes all characters from offset to the end.
Examples
Extracts first 5 characters: 'Hello'
Bash Scripting
text="Hello World"
echo ${text:0:5}
Extracts from position 6 to end: 'World'
Bash Scripting
text="Hello World"
echo ${text:6}
Offset 10 is beyond string length, so output is empty
Bash Scripting
text="Hello"
echo ${text:10:3}
Length 5 is longer than remaining string, extracts from offset 1 to end: 'i'
Bash Scripting
text="Hi"
echo ${text:1:5}
Sample Program
This script extracts parts of a date and file type from a filename string using substring extraction. It shows how to get fixed parts by position and length, and also how to get the last characters using a negative offset.
Bash Scripting
#!/bin/bash

full_text="2024-06-15_report.txt"

# Extract year (first 4 characters)
year=${full_text:0:4}

# Extract month (characters 5 and 6)
month=${full_text:5:2}

# Extract day (characters 8 and 9)
day=${full_text:8:2}

# Extract file type (last 3 characters)
file_type=${full_text: -3}

# Print all extracted parts
echo "Year: $year"
echo "Month: $month"
echo "Day: $day"
echo "File type: $file_type"
OutputSuccess
Important Notes
Time complexity is O(length) because it copies the substring characters.
Space complexity is O(length) for the new substring variable.
Common mistake: forgetting that offset starts at 0, so the first character is position 0, not 1.
Use substring extraction when you know exact positions. Use other tools like cut or awk if you need more flexible splitting.
Summary
Substring extraction lets you get part of a string by position and length.
Offset starts at 0, and length is optional.
It is useful for fixed-format strings like dates or filenames.