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

241

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


269

You can do like this:

#!/bin/bash

v="some string.rtf"

v2=${v::-4}

echo "$v --> $v2"

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


189

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: