Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 724
user2148564 Avatar asked Dec 16 '22 11:12

user2148564


2 Answers

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 
like image 125
DVK Avatar answered Apr 19 '23 08:04

DVK


This can work:

$ awk '{if ($2~"b") a=NR} END{print a}' your_file

We check every second file being "b" and we record the number of line. It is appended, so by the time we finish reading the file, it will be the last one.

Test:

$ awk '{if ($2~"b") a=NR} END{print a}' your_file
6

Update based on sudo_O advise:

$ awk '{if ($2=="b") a=NR} END{print a}' your_file

to avoid having some abc in 2nd field.

It is also valid this one (shorter, I keep the one above because it is the one I thought :D):

$ awk '$2=="b" {a=NR} END{print a}' your_file
like image 23
fedorqui 'SO stop harming' Avatar answered Apr 19 '23 06:04

fedorqui 'SO stop harming'