How to strip the last n characters from a string in Bash?

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.

 

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:

Leave a Reply