How to Get Last Word of a String in Bash (With Examples)


Often you may want to get the last word of a string in Bash.

You can use the following methods to do so:

Method 1: Get Last Word of String

echo "this is a string" | awk '{print $NF;}'

This particular example extracts the last word from “this is a string”.

Method 2: Get Last Word of Each Line in File

awk 'NF>1{print $NF}' my_file.txt

This particular example extracts the last word from each line in the file named my_file.txt.

Note that both of these examples use the NF statement in awk, which stands for “number of fields” and extracts the last field (i.e. last word) from a given string.

The following examples show how to use each method in practice.

Example 1: Get Last Word of String in Bash

Suppose that we have the following string:

  • ” this is a string”

And suppose that we would like to extract only the last word from the string.

We can use the following syntax to do so:

echo "this is a string" | awk '{print $NF;}'

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

Bash get last word of string

Note that we’re able to extract “string” – which represents the last word in the string. 

Also note that this syntax is capable of extracting the last word in the string even if there are trailing or leading spaces in the string.

Example 2: Get Last Word of Each Line in File

Suppose that we have a file named coaches.txt.

We can use the cat command to view the contents of this file:

Bash get last word of each line in file

Suppose that we would like to extract the last word from each line in the file.

We can use the following syntax to do so:

awk 'NF>1{print $NF}' coaches.txt

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

Bash get last word in each line in file

Note that we’re able to extract the last word in each line of the file.

Related Tutorials

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

Bash: How to Extract Text Between Two Strings
Bash: How to Replace Multiple Characters in String
Bash: How to Replace All Occurrences of String in File

Leave a Reply