[bash] 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 related to bash

The answer is


What worked for me was:

echo "hello world" | rev | cut -c5- | rev
# hello w

But I used it to trim lines in a file so that's why it looks awkward. The real use was:

cat somefile | rev | cut -c5- | rev

cut only gets you as far as trimming from some starting position, which is bad if you need variable length rows. So this solution reverses (rev) the string and now we relate to its ending position, then uses cut as mentioned, and reverses (again, rev) it back to its original order.


This worked for me by calculating size of string.
It is easy you need to echo the value you need to return and then store it like below

removechars(){
        var="some string.rtf"
        size=${#var}
        echo ${var:0:size-4}  
    }
    removechars
    var2=$?

some string


In this case you could use basename assuming you have the same suffix on the files you want to remove.

Example:

basename -s .rtf "some string.rtf"

This will return "some string"

If you don't know the suffix, and want it to remove everything after and including the last dot:

f=file.whateverthisis
basename "${f%.*}"

outputs "file"

% means chop, . is what you are chopping, * is wildcard


You could use sed,

sed 's/.\{4\}$//' <<< "$var"

EXample:

$ var="some string.rtf"
$ var1=$(sed 's/.\{4\}$//' <<< "$var")
$ echo $var1
some string

I tried the following and it worked for me:

#! /bin/bash

var="hello.c"
length=${#var}
endindex=$(expr $length - 4)
echo ${var:0:$endindex}

Output: hel


Hope the below example will help,

echo ${name:0:$((${#name}-10))} --> ${name:start:len}

  • In above command, name is the variable.
  • start is the string starting point
  • len is the length of string that has to be removed.

Example:

    read -p "Enter:" name
    echo ${name:0:$((${#name}-10))}

Output:

    Enter:Siddharth Murugan
    Siddhar

Note: Bash 4.2 added support for negative substring


Using Variable expansion/Substring replacement:

${var/%Pattern/Replacement}

If suffix of var matches Pattern, then substitute Replacement for Pattern.

So you can do:

~$ echo ${var/%????/}
some string

Alternatively,

If you have always the same 4 letters

~$ echo ${var/.rtf/}
some string

If it's always ending in .xyz:

~$ echo ${var%.*}
some string

You can also use the length of the string:

~$ len=${#var}
~$ echo ${var::len-4}
some string

or simply echo ${var::-4}


You can do like this:

#!/bin/bash

v="some string.rtf"

v2=${v::-4}

echo "$v --> $v2"

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

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