The Memory Bank

...for memory blanks

Site Tools


get_last_n_chars

This is an old revision of the document!


Get the last n characters from a bash variable

To extract the last 'n' characters from a string in Bash, the most common and efficient method is using string slicing with a negative offset. Using String Slicing:

string="This is a sample string"
n=5 # Number of last characters to extract

last_n_chars="${string: -$n}"
echo "$last_n_chars"
get_last_n_chars.1753920517.txt.gz · Last modified: (external edit)