How to extract a substring from the end?

QuestionsQuestions4 SkillsProDec, 13 2025
0255

That's an excellent follow-up question! Extracting from the end of a string is a common requirement, and Bash provides a neat way to do it using a slightly modified version of the same substring syntax you just learned.

To extract a substring from the end, you use a negative starting position.

The syntax then becomes: ${variable: -offset:length}

Let's break it down:

  • variable: The string variable you want to extract from (e.g., STRING).
  • : (colon followed by a space): This is crucial! When using a negative offset, there must be a space after the colon to distinguish it from parameter expansion for default values.
  • -offset: This is a negative number indicating the position relative to the end of the string.
    • -1 refers to the last character.
    • -2 refers to the second to last character, and so on.
  • :length (optional): This specifies how many characters to extract from that negative offset point towards the end.
    • If length is omitted, it extracts everything from the offset to the end of the string.

Let's try an example:

#!/bin/bash

MY_STRING="Hello LabEx World!"

echo "Original string: $MY_STRING"

# --- Example 1: Extract the last character ---
LAST_CHAR=${MY_STRING: -1}
echo "Last character: $LAST_CHAR" # Output: !

# --- Example 2: Extract the last 5 characters ---
LAST_FIVE=${MY_STRING: -5}
echo "Last 5 characters: $LAST_FIVE" # Output: rld!

# --- Example 3: Extract from the 6th character from the end, for 3 characters ---
# Counting from the end:
# H e l l o   L a b E x   W o r l d !
#                         ^
#                         -6
SUB_FROM_END=${MY_STRING: -6:3}
echo "Substring from 6th from end, 3 chars: $SUB_FROM_END" # Output: Wor

Key takeaways for negative offsets:

  1. Space is essential: ${STRING: -offset} (with a space) vs. ${STRING:-defaultvalue} (without a space which provides a default value if STRING is unset or null).
  2. Offset is from the end: -1 is the last character, -2 is the second to last, etc.
  3. Length is optional: If omitted, it extracts to the very end of the string.
  4. 0-indexed logic still applies, but from the end: Think of it as counting 0 from the last character backwards. So ${STRING: -1} is char_at_len-1, ${STRING: -2} is char_at_len-2, etc.

You can add these examples to your string_operations.sh file to experiment if you like!

Would you like to try modifying your script to extract, say, the last word from your STRING variable?

0 Comments

no data
Be the first to share your comment!