How to remove last n characters from a string in Bash?


I have a variable var in a Bash script holding a string, like:

echo $var
"some string.rtf"

I want to remove the last 4 characters of this string and assign the result to a new variable var2, so that

echo $var2
"some string"

How can I do this?

This question is tagged with bash

~ Asked on 2014-12-26 15:05:16

The Best Answer is


You can do like this:


v="some string.rtf"


echo "$v --> $v2"

~ Answered on 2014-12-26 15:11:03


To remove four characters from the end of the string use ${var%????}.

To remove everything after the final . use ${var%.*}.

~ Answered on 2014-12-26 15:09:51

Most Viewed Questions: