0

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.

Community
  • 1
  • 1
kir
  • 581
  • 1
  • 6
  • 22

3 Answers3

3

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.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
2

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.

user3159253
  • 16,836
  • 3
  • 30
  • 56
  • Also it seems I've just found a bug/a strange behaviour in bash: `bash -c 'echo \$@=\"$@\";' a b c` gives me `$@="b c"` :-). That's why I need an additional `_` between the command argument `{}` – user3159253 Feb 15 '14 at 00:37
1

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.

BMW
  • 42,880
  • 12
  • 99
  • 116