bash – getting part of variable (e.g. last 4 characters and prefix)

Recently, I had this small issue, how to split variable in bash without too much effort. I wanted to split it into two parts: prefix and suffix.

There were few assumptions, when it comes to variable value.

– length of variable is >= 5
– it has fixed length of suffix (4 characters)
– prefixes lengths can vary

variable="123451234"
prefix=${variable::${#variable}-4}
suffix=${variable: -4}
echo "variable: $variable prefix: $prefix suffix $suffix"

Leave a comment

Your comment