In Linux, we constantly work with string and text files; whether working with log files or documents, text manipulation is one process we cannot escape.
This guide will show you how to locate the last occurrence of a string in a file in Linux. Linux has many tools that can help perform tasks. However, for simplicity, we will stick to the readily available tools in all major Linux distributions.
Method 1: Using Grep
Global Regular Expression Print, known as grep, is a popular and powerful text manipulation tool.
It works by accepting input from standard input or a file and searches for a specified pattern. Once grep finds the specified pattern, it prints the result to the standard output. The specified pattern can be a single string or a complex regex.
Suppose we have the file auth.log (/var/log/auth.log). To find the last occurrence of a string (uid=0), we can use the command:
The output will be as shown below:
The command is relatively simple. We start by finding the string we require using grep. Next, Grep will list all the string occurrences, and finally, we pipe the output to the tail and locate the last line of the output.
You can modify the command above to get the last five occurences of the string as:
Method 2: AWK
AWK is another popular string manipulation language. AWK is very powerful as it offers incredible features compared to other text manipulation programs.
To find a similar string as above, we can use a command as:
Similarly, this will show the last occurrence of the string as:
That is it for this one. In this quick tutorial, we discussed two main methods to find the last occurrence of a string using grep and awk.