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. |
grep -B 3 -A 4 “test” | Display result lines with 3 preceding and 4 following lines against matched term. |
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. “-mtime 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” {} \;
Note: there is much faster alternative to search for files – command “locate”. Although it is not necessary available in all linux distributions by default. But can be manually installed everywhere. It uses own filesystem index which is refreshed approx. once a day. So if we need to perform a very fast search for older files, locate is the right command. Example:
locate -b ‘filename’ # -b enables search against fragment in file name. Incase of strict matching – use “-w”.