0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Extract Substring from a String

In Bash, extract a substring using ${string:position:length}, where position is the start index (0-based) and length is how many characters to take, for example: substring=${string:2:5}.
📋

Examples

Inputstring='HelloWorld', position=0, length=5
OutputHello
Inputstring='abcdefg', position=2, length=3
Outputcde
Inputstring='short', position=3, length=10
Outputrt
🧠

How to Think About It

To extract a substring in Bash, think of the string as a sequence of characters starting at index 0. You choose where to start and how many characters to take. Bash lets you do this easily with ${string:position:length} syntax, which slices the string from the start position for the given length.
📐

Algorithm

1
Get the input string.
2
Decide the start position (0-based index) for the substring.
3
Decide the length of the substring to extract.
4
Use Bash parameter expansion <code>${string:position:length}</code> to get the substring.
5
Print or return the extracted substring.
💻

Code

bash
#!/bin/bash
string="HelloWorld"
position=2
length=5
substring=${string:position:length}
echo "$substring"
Output
lloWo
🔍

Dry Run

Let's trace extracting substring from 'HelloWorld' starting at position 2 with length 5.

1

Set variables

string='HelloWorld', position=2, length=5

2

Extract substring

substring=${string:2:5} → 'lloWo'

3

Print result

echo 'lloWo'

StepOperationValue
1stringHelloWorld
2substring extractionlloWo
3outputlloWo
💡

Why This Works

Step 1: Parameter Expansion

Bash uses ${string:position:length} to slice strings without external commands.

Step 2: Zero-based Indexing

The position starts at 0, so 2 means the third character.

Step 3: Length Limits

If length exceeds string end, Bash returns characters up to the string's end.

🔄

Alternative Approaches

Using cut command
bash
string="HelloWorld"
echo "$string" | cut -c3-7
Uses external command; less efficient but simple for fixed positions.
Using expr substring
bash
string="HelloWorld"
expr substr "$string" 3 5
Legacy method; requires external command and 1-based indexing.

Complexity: O(n) time, O(n) space

Time Complexity

Extracting a substring takes time proportional to the length of the substring, O(n), where n is the substring length.

Space Complexity

The substring requires additional space proportional to its length, O(n), as it creates a new string.

Which Approach is Fastest?

Bash parameter expansion is fastest as it is built-in and avoids external commands, unlike cut or expr.

ApproachTimeSpaceBest For
Parameter ExpansionO(n)O(n)Fast, built-in, simple substring extraction
cut commandO(n)O(n)Simple fixed-position extraction, external tool
expr substringO(n)O(n)Legacy scripts, external tool, 1-based indexing
💡
Remember Bash substring indexing starts at 0, unlike some tools that start at 1.
⚠️
Forgetting that Bash substring positions start at 0, causing off-by-one errors.