Remove substring if string starts with it using bash script – Code Example

Total
0
Shares

Let’s see the bash script code example to remove substring from a string if that substring appears in the beginning of the string. It is different from first occurrence as it only removes if string holds the substring in the beginning.

Code Example –

1. Function

#!/bin/bash

string_remove_match_from_left() {
    echo "${1##$2}"
}

string_remove_match_from_left "nothing is strong enough to hurt nothings of society" "not"

# Output:
# hing is strong enough to hurt nothings of society

2. Remove first character if its a vowel –

# string will remain unchanged because it starts with consonant
string_remove_match_from_left "no remove vowels from this" "[aeiou]"

# Output:
# no remove vowels from this

3. Remove first character if its a numeric digit –

string_remove_match_from_left "remove 86 from this, nope" "[0-9]"

# Output:
# remove 86 from this, nope

4. Remove one empty space if string starts with empty spaces –

string_remove_match_from_left " remove space from this. sure first only" "[[:space:]]"

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

Inspired from Dylan Araps

Live Demo

Open Live Demo