kir
kir

Reputation: 581

Grep only last line after find needed files

Hi guys I have an extended question from this thread

I need to find some files given file name and use grep on the last lines of these files to find a certain string.

I currently have:

find my_dir/ -name "*filename*" | xargs grep 'lookingfor'

I'm new to using these commands so much help would be appreciated. Thank you in advance.

Upvotes: 0

Views: 3514

Answers (3)

BMW
BMW

Reputation: 45243

Using find + awk + wc -l

find  my_dir -name '*filename*' -type f -exec awk 'NR>count-100{print FILENAME, $0}' count=$(wc -l < {}) {} +

Adjust 100 to the number of last lines you want.

Upvotes: 1

user3159253
user3159253

Reputation: 17455

I would go with

find  my_dir -name '*filename*' -type f \
     -exec /bin/bash -c '(tail -5 "$1" | grep -q lookingfor) && echo "$1"' _ {} \;

This way you will correctly handle all (well, hopefully all :-)) filenames, even those with " and other strange symbols within. Also I would suggest explicitly call /bin/bash because /bin/sh may be linked on a crippled sh-variant like ash, sash and dash.

Upvotes: 2

fedorqui
fedorqui

Reputation: 289795

You can for example do:

find my_dir/ -name "*filename*" -exec sh -c "tail -200 {} | grep lookingfor" \;

setting 200 to the number of last lines you want.

Upvotes: 3

Related Questions