Linux command to get the last appearance of a string in a text file


I want to find the last appearance of a string in a text file with linux commands. For example

1 a 1
2 a 2
3 a 3
1 b 1
2 b 2
3 b 3
1 c 1
2 c 2
3 c 3

In such a text file, i want to find the line number of the last appearance of b which is 6.
I can find the first appearance with

awk '/ b / {print NR;exit}' textFile.txt

but I have no idea how to do it for the last occurrence.

Best Solution

cat -n textfile.txt | grep " b " | tail -1 |  cut -f 1
  • cat -n prints the file to STDOUT prepending line numbers.
  • grep greps out all lines containing "b" (you can use egrep for more advanced patterns or fgrep for faster grep of fixed strings)
  • tail -1 prints last line of those lines containing "b"
  • cut -f 1 prints first column, which is line # from cat -n

Or you can use Perl if you wish (It's very similar to what you'd do in awk, but frankly, I personally don't ever use awk if I have Perl handy - Perl supports 100% of what awk can do, by design, as 1-liners - YMMV):

perl -ne '{$n=$. if / b /} END {print "$n\n"}' textfile.txt