How to remove the last several characters of a string? I have not considered this problem until recently. It turns out there are quite a few methods to delete the last (n) character(s) from a string.
To delete the last character, you can use:
echo ${s%?}
To delete the last two letters, you can use:
echo ${s%??}
To remove the last 3 characters, you can use:
echo ${s%???}
You can see the number of question marks is equal to the number of characters you want to remove from the string s.
Another method is more general:
echo ${s::${#s}-1}
The general syntax to get a sub-string of a string is :
substring=${s:start:length}
If start is empty, it is defaulted to 0. If length is empty, it is also defaulted to 0. So,
echo ${s:0:}
will display empty.
If “:length” is missing, the length is defaulted to the length of the original string, so
echo ${s:0}
will display the whole string.
${#s} will expand to the length of the string. So ${s::${#s}-1} will delete the last character from s. Similarly, ${s::${#s}-2} will remove the last two characters from s.
You may see the following method to get rid of the last character from s:
echo ${s::-1}
But it only works for higher bash version. At least it does not work on bash 4.1.2. How to check the version of bash on your system? You can use the following methods:
- echo “${BASH_VERSION}”
- bash –version
- press the key ctrl+x and ctrl+v
Note that the command “bash -v” or “bash -V” won’t tell you the bash version. Instead, it will run another instance of bash.