Substring Extraction
Substring extraction is like cutting a slice out of a long ribbon. You say where to start cutting and how long a piece you want.
In this page:
Syntax
${variable:start:length}
${variable:start}
Substring Extraction
${variable:start:length} extracts a portion of a string starting at a given index (0-based) for a given number of characters. Omitting length extracts everything from start to the end.
This is Bash's built-in equivalent of a substring function found in other languages.
Note:
A negative
start, like ${var: -3}, extracts from the end of the string (note the required space before the minus).Example: Substring Extraction
#!/bin/bash
text="Hello, Bash World!"
echo "${text:0:5}"
echo "${text:7:4}"
echo "${text:7}"
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
${str:1:3}and expecting3to be the end index, when it is the length. - Forgetting that offsets start at 0.
- Using a negative offset without a space, as in
${str:-3}, which means a default value; write${str: -3}.
🔒
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: