I have a scenario which I am implementing

fetch only the last occurrence of matched keyword found

for example : I have a file called demo.txt contains lots of data

egrep -in '<NAME ="ABC_DEF_GHI">' /d/demo.txt

Line Number 11 : <NAME ="ABC_DEF_GHI">
Line Number 12 : <NAME ="ABC_DEF_GHI">
Line Number 34 : <NAME ="ABC_DEF_GHI">
Line Number 46 : <NAME ="ABC_DEF_GHI">
Line Number 67 : <NAME ="ABC_DEF_GHI">
Line Number 78 : <NAME ="ABC_DEF_GHI">

But I want to fetch the last occurrence of the keyword matched <NAME ="ABC_DEF_GHI">

output should only be

Line Number 78 : <NAME ="ABC_DEF_GHI"> -> as its last occurrence

I tried this below code not working

tail -f -n 1 /d/demo.txt | egrep -in '<NAME ="ABC_DEF_GHI">'
  • You should describe in more detail what "not working" means. I guess you get no output if the last line of the file doesn't match your pattern. – Bodo Nov 15 '19 at 12:59
  • The reason why your line is not working is two-fold: for one, you should not use tail -f; this is for cases where you want to inspect a file where you expect that some process (e.g. the syslogger) keeps appending text. Second, the order of your commands is wrong: your example would output the last line of demo.txt regardless of its content, and the grep call would only output anything if the last line happens to contain your pattern. You need to reverse the order: filter your file through grep to ensure only matching lines are printed and then use tail to show only the last. – AdminBee Nov 15 '19 at 13:11
  • You can probably process the original XML file directly. Is this an XY Problem? – roaima Nov 15 '19 at 14:07

Do the tail after grep

egrep -in '<NAME ="ABC_DEF_GHI">' /d/demo.txt | tail -1

As you are searching for a literal string, not for an extended regular expresseion, I suggest to use fgrep instead of egrep.

fgrep -in '<NAME ="ABC_DEF_GHI">' /d/demo.txt | tail -1
| improve this answer | |

To avoid running grep on the whole file, reverse it and take the first occurrence:

tac file | egrep -in -m1 'pattern'
| improve this answer | |
  • reversing a big file with tac is probably more expensive than grep on the whole file. – Bodo Nov 15 '19 at 14:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.