Grep only last line after find needed files

China☆狼群 提交于 2021-02-04 21:38:18

问题


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.


回答1:


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.




回答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.




回答3:


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.



来源:https://stackoverflow.com/questions/21791657/grep-only-last-line-after-find-needed-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!