How do I remove the last characters from a string?

To remove everything from after the last _ in var and assign the result to var2:

var2=${var%_*}

The parameter expansion ${parameter%word} removes the pattern word (_* in this case) from the end of the value of the given variable.

The POSIX standard calls this a "Remove Smallest Suffix Pattern" parameter expansion.

To remove the last underscore and the 10 characters after it, use

var2=${var%_??????????}

To remove characters corresponding to a date string such as the one in your example, use

var2=${var%_[0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]}

Which pattern you use depends on how carefully you want to perform the match.


You actually want to remove the trailing 11 characters from the string; here's another way to do it:

$ var=type_cardio_10-11-2017
$ var2=${var%???????????}
$ echo "$var2"
type_cardio

Another approach in bash:

echo "${var::-10}"

Or in older versions:

echo "${var::${#var}-10}" #or
echo "${var: : -10}"