Remove substring from end of string using bash script – Code Example

This article will provide you a bash script code to remove substring from end of string. This code will only remove the substring pattern if it appears at the very end of the string. You can use it directly in your projects.

Code Example –

1. Function –

#!/bin/bash

string_remove_match_from_end() {
    echo "${1%%$2}"
}

string_remove_match_from_end "nothing is strong enough to hurt nothings of society. cannot" "not"

# Output:
# nothing is strong enough to hurt nothings of society. can

2. Remove last vowel from string, If string ends with vowel –

string_remove_match_from_end "remove vowels from end of this line" "[aeiou]"

# Output:
# remove vowels from end of this lin

3. Remove last numeric digit from string, if string ends with digit –

string_remove_match_from_end "remove 86 from this, nope. Will remove 0" "[0-9]"

# Output:
# remove 86 from this, nope. Will remove

4. Remove single blank space at the end of the string –

string_remove_match_from_end " remove space from this. sure end only " "[[:space:]]"

# Output:
#  remove space from this. sure end only

Inspired from Dylan Araps

Live Demo

Open Live Demo