Bash: How to Get Last N Characters from String


Often you may want to use Bash to get the last N characters from a string.

The easiest way to do so is by using the tail command, which allows you to display the last part of a given input.

You can use the following basic syntax with the tail command to get the last character from a string:

echo -n $my_string | tail -c 1

This particular example will get just the last character from the string variable named my_string.

Note that you can replace 1 with any number you would like to instead get the last N characters from a string.

Note that the -n operator is used so that the echo command does not include a newline at the end and the -c is used to specify that we would like to extract characters as opposed to something else like -b to extract bytes.

The following example shows how to use this syntax in practice.

Example: How to Get Last N Characters from String in Bash

Suppose we have the following string that represents the employee ID for a manager at a particular company:

  • Manager1430Department15

Suppose that we would only like to get the last character from this string.

We can use the following syntax to do so:

employee_ID="Manager1430Department15"
echo -n $employee_ID | tail -c 1

The following screenshot shows how to use this syntax in practice:

Bash get last character of string

Notice that this returns 5, which is the last character in the string.

Note that we can also replace the 1 in the syntax to instead extract a different number of characters from the end of the string.

For example, we can use the following syntax to instead get the last 6 characters from the string:

employee_ID="Manager1430Department15"
echo -n $employee_ID | tail -c 6

The following screenshot shows how to use this syntax in practice:

Bash get last n characters of string

Notice that this returns ment15, which represents the last 6 characters in the string.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Check if String Starts with Specific Value
Bash: How to Count Number of Words in String
Bash: How to Count Number of Characters in String

Leave a Reply