Linux to get the last line appearance in a text file

I want to find the last occurrence of a string in a text file using linux commands. for instance

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 this text file, I want to find the line number of the last occurrence of b, which is 6. I can find the first occurrence with

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

but I do not know how to do this for the latter case.

+4
source share
3 answers
 cat -n textfile.txt | grep " b " | tail -1 | cut -f 1 
  • cat -n prints the file as line numbers containing STDOUT lines.
  • grep selects all lines containing "b" (you can use egrep for more advanced templates or fgrep for faster grep fixed lines)
  • tail -1 prints the last line of these lines containing "b"
  • cut -f 1 prints the first column, which is row # from cat -n

Or you can use Perl if you want (very similar to what you would do in awk, but to be honest, I personally never use awk if I have Perl - 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 
+9
source

This may work:

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

We check every second file for "b" and write the number of lines. It is added, so by the time we finish reading the file, it will be the last.

Test:

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

Update based on sudo_O tip :

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

to avoid abc in the second field.

This is also true (in short, I keep one above, because this is the one I thought: D):

 $ awk '$2=="b" {a=NR} END{print a}' your_file 
+3
source

Another approach, if $ 2 is always grouped (may be more efficient than waiting until the end):

 awk 'NR==1||$2=="b",$2=="b"{next} {print NR-1; exit}' file 

or

 awk '$2=="b"{f=1} f==1 && $2!="b" {print NR-1; exit}' file 
0
source

Source: https://habr.com/ru/post/1479542/


All Articles