Remove 1st occurrence of substring in string bash script – Code Example

Total
0
Shares

Get bash script code example to remove first occurrence of substring from string. You can match through a normal substring or a regex.

Code Example –

1. Function –

#!/bin/bash

string_remove_first_match() {
    echo "${1/$2}"
}

string_remove_first_match "I am not animal lover not" "not"

# Output:
# I am  animal lover not

2. Remove first occurrence of vowel –

string_remove_first_match "remove all vowels from this" "[aeiou]"

# Output:
# rmove all vowels from this

3. Remove first occurrence of numeric digit –

string_remove_first_match "remove 86 from this" "[0-9]"

# Output:
# remove 6 from this

4. Remove first occurrence of blank space –

string_remove_first_match "remove space from this" "[[:space:]]"

# Output:
# removespace from this

Inspired from Dylan Araps

Live Demo

Open Live Demo