Wednesday 24 February 2016

Find command example in linux

Find command used to search both files and directory in a linux system.



  1. How to find core files

# find / -name core
  1. How to view 10 days old files
find /path/to/files* -mtime +10
  1. How to find file those having 2gb size
#find . -size +20000k -exec du -h {} \;
  1. to search inode number and seeing content inside that file
                         find / -inum number -exec cat number {} \;      or find . -inum 1610620106 -exec cat i {} \;
  1. to search inode number and delete inode number file
                               find . -inum number -exec rm -i {} \;
  1. Find the inode number file eg:123 and move that file to aaa folder
                     i=123; find . -inum $i -exec mv -i {} aaa \;
         7.how to find a particular file in particular directory and search for a particular string occurance

find /tmp/aaa/ -type f -and -name "1.txt" -exec grep -i "s" {} \;

(we can use "-and " "-not " "-or" for condition)


8. How to find a file which is bigger than +500k size

find / -type f -size +500k 


9. How to search directory or file based on ownership

for directory:
find /tmp/ -type d -user test

for file:
find /tmp/ -type f -user test -name "filename"

10. How to search for file which has 777 permission

find /tmp/ -perm 777 (return all the file with 777 permission)

or

find /tmp/ -perm 777 -name "1.txt" (return only particular 1.txt file which matches 777 permission )

11. How to find total number of file in a certain directory

If you want to exclude subdirectories, you need a heavier duty tool than ls.
$ find targetdir -maxdepth 1 -type f | wc -l  # find all files in current target directory and exclude sub-directory

find targetdir -type f | wc -l     #  find all files including files in sub and sub-sub-directory

-type f ensures that the find command only returns regular files for counting (no subdirectories).
By default, the find command traverses into subdirectories for searching. -maxdepth 1 prevents find from traversing into subdirectories. If you do want to count files in the subdirectories, just remove -maxdepth 1 from the command line.
Note that the find command does NOT classify a symbolic link as a regular file. Therefore, the above find -type f command does not return symbolic links. As a result, the final count excludes all symbolic links.
To include symbolic links, add the -follow option to find.
$ find targetdir -follow  -maxdepth 1 -type f | wc -l
To find number of directories present in a certain directory
$ find targetdir -maxdepth 1 -type d | wc -l        # leaves sub sub-directories
$ find targetdir -type d | wc -l     #  find all sub and sub-sub-directory










No comments:

Post a Comment