Find and grep

grep command syntax

grep "text string to search" directory-path
Examples

To search for a string called redeem reward in all text files located in /home/tom/*.txt directory, use

$ grep "redeem reward" /home/tom/*.txt

To recursively search for a text string all files under each directory, use -r option:

$ grep -r "redeem reward" /home/tom

find command syntax

$ find path expression

Using the command line, you can search for files larger than a given filesize using

$find path -size +1024k

$find path -size +5M -print

Note the -print is the default and assumed

Using the command line, you can search for files with name

$find path -name '*.AVI'

Find all files with the name program.c starting at root directory (i.e / directory)

$ find path -name 'program.c' 2>/dev/null

$ find path -name 'program.c' 2>errors.txt

Note : 2>/dev/null  in case any error messages '2' pop up simply send them '>' to /dev/null i.e. simply discard all error messages.

$ find /home/david -name 'index*'
$ find /home/david -iname 'index*'
The 1st command would find files having the letters index as the beginning of the file name. The search would be started in the directory /home/david and carry on within that directory and its subdirectories only.
The 2nd command would search for the same, but the case of the filename wouldn't be considered. So all files starting with any combination of letters in upper and lower case such as INDEX or indEX or index would be returned.

$ find -name met*

The above command would start searching for the files that begin with the letters 'met' within the current directory and the directories that are present within the current directory. Since the directory is not specified as the the second parameter, Linux defaults to using the current directory as the one to start the search in.

$ find /mp3collection -name '*.mp3' -size -5000k
$ find / -size +10000k

The 1st command would find within a directory called /mp3collection, only those mp3 files that have a size less than 5000 Kilobytes ( < 5MB)
The 2nd command would search from the / directory for any file that is larger than 10000k (> 10MB)

$ find /home/david -amin -10 -name '*.c'
$ find /home/david -atime -2 -name '*.c'
$ find /home/david -mmin -10 -name '*.c'
$ find /home/david -mtime -2 -name '*.c'

The 1st commmand searches for those files that are present in the directory /home/david and its subdirectoires which end in .c and which have been accessed in the last 10 minutes.
The 2nd command does the same but searches for those files that have been accessed in the last 10 hours.
The 3rd and the 4th commands do the same as the 1st and 2nd commands but they search for modified files rather than accessed files. Only if the contents of the files have been modified, would their names be returned in the search results.

 

 

Subject