Linux

Common usages of grep and find in Linux

It is so common need to dig some info in Linux remote machines where you have just a terminal access. Effectiveness of searching might be crucial in finding necessary files and content. Here are couple of commands come to help as:

  • grep – search in file contents
  • find – search by file name

It happens that sometimes quite difficult to recall exact commands to do the job. Here are some of variations for quick copy-paste which might be useful:

grep

Command Description
grep “text” * In current folder. Not recursive.
grep -r “text” * In current folder. Recursive.
grep -ir “text” filename1 filename2 Particular files. Case insensitive. Recursive.
grep -wr “text” *.log Only whole word match. Recursive. File name pattern applied.
grep -v “text” * Files which does not contain fragment “text”. Inversion.
grep -n “test” * Add lines numbers to output.

find

Command Description
find . -name “*.txt” Current folder. Recursive. Case sensitive.
find . -iname “TEST*” Case insensitive.
find /mnt/c -size +100M Specific folder. All files with size over 100Mb.
find . -name ‘*.log’ -cmin -5 All .log files updated in last 5 minutes. “-imtime 5” would stand for las 5 days.
find . \( -name ‘*.txt’ -o -name ‘*.log’ \) Multiple filtering patterns, combined with operator “-o” (operator OR).
find . -name “test*” -type f Find only files which start with “test”. “-d” would stand for folders.

Finally we can combine those two commands together for even more effective output. Here we can leverage argument “-exec” of “find” command. It lets execute another command for the stream output of find:

find . -iname “tes*” -exec grep “one” {} \;

Probably we need to search for files with some content and just receive a list of them, not each occurrance of fragment. Then lets add “-l” to get unique file list and “-H’ to get file name:

find . -iname “tes*” -exec grep -Hl “one” {} \;

 


Advertisement

About Danas Tarnauskas

Leave a Reply

Your email address will not be published.