Often you may want to use Bash to remove the last N characters from a string.
There are two common ways to do so:
Method 1: Remove Last N Characters Using Parameter Expansion
new_string="${my_string%????}"
This particular example will remove the last four characters from the string variable named $my_string and save the results in a new variable named $new_string.
Note that this method uses a technique known as parameter expansion in Bash and the number of question mark ( ? ) symbols indicates the number of characters to remove from the end of the string.
Method 2: Remove Last N Characters Using sed
new_string=$(sed 's/.\{4\}$//' <<< "$my_string")
This particular example will also remove the last four characters from the string variable named $my_string and save the results in a new variable named $new_string.
Simply replace the 4 in the code with a different number to remove a different number of characters from the end of the string.
The following examples show how to use each method in practice.
Example 1: Remove Last N Characters from String Using Parameter Expansion
Suppose we have the following string stored in a variable named $my_string in Bash:
- The Dallas Mavericks
Suppose that we would like to remove the last four characters from the string.
One way to do so is by using parameter expansion in Bash with the following syntax:
my_string="The Dallas Mavericks"
new_string="${my_string%????}"
echo $new_string
The following screenshot shows how to use this syntax in practice:

Notice that the new variable named $new_string contains the string from the original variable with the last 4 characters removed:
- The Dallas Maver
Example 2: Remove Last N Characters from String Using sed
Once again, suppose we have the following string stored in a variable named $my_string in Bash:
- The Dallas Mavericks
Suppose that we would like to remove the last four characters from the string.
One way to do so is by using the following syntax with sed:
my_string="The Dallas Mavericks"
new_string=$(sed 's/.\{4\}$//' <<< "$my_string")
echo $new_string
The following screenshot shows how to use this syntax in practice:

Notice that the new variable named $new_string contains the string from the original variable with the last 4 characters removed:
- The Dallas Maver
Notice that the results of this method match the results from the previous method.
Feel free to use whichever method you prefer.
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
