Bash: How to Remove Prefix from a String


You can use the following syntax in Bash to remove a prefix from a string:

my_string_no_prefix=${my_string/#$my_prefix}

This particular example will remove the prefix specified by the my_prefix variable from the string variable named my_string and save the results to a new variable named my_string_no_prefix.

Note that by using #$my_prefix we specify that the string stored in the my_prefix variable should only be removed if it is found at the beginning of the string.

Without including the # character, the string specified by the my_prefix variable could be removed from the string if it is found anywhere in the string.

The following example shows how to use this syntax in practice.

Example: How to Remove Prefix from a String in Bash

Suppose that we create a string variable named my_string that contains the following text in Bash:

  • TheDallasMavericks

Suppose that we would like to remove the prefix “The” from this string variable.

We can use the following syntax to do so:

my_string="TheDallasMavericks"
my_prefix="The"

my_string_no_prefix=${my_string/#$my_prefix}
echo $my_string_no_prefix

The following screenshot shows how to use this syntax in practice:

Bash remove prefix from string

Notice that when we use the echo statement to view the new variable named my_string_no_prefix we can see that it contains the same text as the my_string variable with the prefix “The” removed.

The new string contains the following text:

  • DallasMavericks

Feel free to use similar syntax to remove a specific prefix from your own string variable in Bash.

Note: If the prefix that you specify does not exist in the string variable then the string will simply remain unchanged.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Check if String Starts with Specific Value
Bash: How to Count Number of Words in String
Bash: How to Count Number of Characters in String

Leave a Reply