Bash: How to Split a String and Get Last Element


Often in Bash you may want to split a string and then get the last element.

There are two common ways to do so:

Method 1: Use echo with ##*

echo "${my_string##*-}"

Method 2: Use echo with awk

echo $my_string | awk -F- '{print $NF}'

Both of these particular examples will split the string variable named my_string using dashes ( – ) as separators and then return only the last element from the split.

The following example shows how to use each method in practice.

Example: How to Split a String and Get Last Element in Bash

Suppose that create a variable named my_string in Bash that contains the following text:

  • “The-Dallas-Mavericks”

Suppose that we would like to split this string using a dash as a separator and then return only the last element.

One way to do so is by using the echo statement with the ##* syntax:

my_string="The-Dallas-Mavericks"
echo "${my_string##*-}"

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

Bash split string and get last element

Notice that this returns Mavericks, which represents the last element after splitting the original string based on where the dashes occur.

Note: The character that comes after ##* specifies the character to use as the separator when performing the split.

Another way to achieve the same result is to use awk and print $NF, which represents “number of fields” and prints only the last element after a string has been split:

my_string="The-Dallas-Mavericks"
echo $my_string | awk -F- '{print $NF}'

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

Bash split string and get last element using awk

Notice that this also returns Mavericks, which is the last element that results from splitting the original string based on dashes.

Feel free to use whichever method you prefer to split a string and get the last element.

Related Tutorials

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

Bash: How to Extract First Number from a String
Bash: How to Split a String into Multiple Variables
Bash: How to Count Number of Words in String
Bash: How to Count Number of Characters in String

Leave a Reply