Monday, August 29, 2011

Unix Find Commands for Developers


Unix's find command searches through one or more directory trees of a file system, locates files based on some criteria.


Here I am listing down some of the way I use find command regularly


###########################################################


find directory -name fileName


###########################################################


Finding files which has been modified less than one day in Unix:


find dir -mtime -1


###########################################################


List all the files & directories in current directory with permission-


find dir -perm 777


###########################################################


Case Insensative


find dir –iname fileNaMe


###########################################################


Find and Delete


find dir -name "*.tmp" | xargs rm -rf


xargs along with find allows to whatever with each search result


find dir -name filename | xargs grep "word"


###########################################################


Find files with size


find dir -size +10000c -size -50000c
find . -size +100k -size -500k


Use c after the number, and specify the size in bytes. Or use k.
The minus sign means "less than," and the plus sign means "greater than


find . -mtime +10 -size +50000c


###########################################################


Files Only


find . -name "my*" -type f


type can be f, d, l -- files, dirs, links


###########################################################


Suppress lines that contain permission denied errors.


find . -name "myfile" | xargs grep -v "Permission denied"


###########################################################


Execute an Action


find dir -name "*.mp3" -type f -exec chmod 644 {} \;


This command changes the permissions of all files with a name ending in .mp3 in the directory dir. 
The action is carried out by specifying the option -exec chmod 644 {} \; in the command. 
For every file whose name ends in .mp3, the command chmod 644 {} is executed replacing {} with the name of the file. 
The semicolon (backslashed to avoid the shell interpreting it as a command separator) indicates the end of the command


find . -exec grep blah {} ;
This is just an example, it is more efficient to pipe the results to the xargs command instead.


###########################################################


find /Users/ashishsharma3/ -iname "Doc*" -mtime -1 -perm 777 -size +100k -size -500k -type f | xargs grep "blah"

find /Users/ashishsharma3/ -iname "Doc*" -mtime -1 -perm 777 -size +100k -size -500k -type f | xargs rm -rf


find /Users/ashishsharma3/ -iname "Doc*" -mtime -1 -perm 777 -size +100k -size -500k -type f -exec chmod 555 {} \;

1 comment: