string


How to: remove prefix and suffix from a variable in bash 3

string="/scripts/log/mount_hello_kitty.log";
prefix="/scripts/log/mount_";
string=${string#$prefix}; #Remove prefix
suffix=".log";
string=${string%$suffix}; #Remove suffix
echo $string; #Prints "hello_kitty"

In the above example we have as input the variable string that contains following /scripts/log/mount_hello_kitty.log.

We want to remove from that variable the prefix, which is /scripts/log/mount_ and the suffix, which is .log.

The above code will replace in place the input that is contained in the variable string and remove the prefix and suffix we defined in the respective variables.

string=${string#$prefix} returns a copy of string after the prefix was removed from the beginning of the variable.

string=${string%$suffix} returns a copy of string after the suffix was removed from the end of the variable.


Remove the last character from a bash variable

The following method, removes the last character from a bash variable by using a regular expression that matches any character.


VAR=${VAR%?};

The functionality ${string%substring} deletes shortest match of $substring from the back of $string.
The question mark ? matches zero or one of the previous regular expression. It is generally used for matching single characters.
So by using ? as our $substring we instruct bash to match any character at the end of the variable and remove it.

Example


$ VAR="Banana";
$ VAR=${VAR%?};
$ echo $VAR;
Banan


Remove the first character from a bash variable

The following method, removes the first character from a bash variable by using a regular expression that matches any character.


VAR=${VAR#?};

The functionality ${string#substring} deletes shortest match of $substring from the front of $string.
The question mark ? matches zero or one of the previous regular expression. It is generally used for matching single characters.
So by using ? as our $substring we instruct bash to match any character at the beginning of the variable and remove it.

Example


$ VAR="Banana";
$ VAR=${VAR#?};
$ echo $VAR;
anana