Thursday, September 20, 2012

UNIX : Find command with useful examples

OS : AIX 6.1
Note : Test the commands containing rm commands carefully at least once in demo environments.


1. Find files under /home1 with extension .c, .pc, .mak and list only filenames
$ find /home1 \( -name "*.pc" -o -name "*.c" -o -name "*.mak" \) -exec ls -1 {} \;

2. Find 10 largest files from current directory
$ find . -type f -exec  du {} \; | sort -nr | head -10

3. Find files greater than 1000 bytes and modified 60 days before
$ find . -size +1000 -a -mtime +60

4. Find  files lesser than 1000bytes and modified in last 60 days
$ find . –size -1000 –a –mtime -60

5. Find files greater than 1000bytes & lesser than 5000bytes but modified exactly 15days ago.
$ find . –size +1000 –size -5000c –mtime 15

6. Find files greater than 1gb
$ find . -type f -size +1048576 -print

7. Find files whose size is zero
$ find . -type f -size 0 –print
OR
$ find . -empty -exec ls {} \;

8. Search evrythng in ur dir that has been modified more recently than ~niraj/test.txt file
$ find $HOME -newer ~niraj/test.txt

9. Negation condition in find example : gzip normal files
$ find . \! -name "*.gz" -exec gzip {} \;

10. Command to move files under current directory except subdirs namely "Study" and "utils" to 'fileOprations' dir is
$ find . \( -name 'Study' -prune -o -name 'utils' -prune -o -type f \) -print | xargs -i mv -f {} ./fileOprations

11. Delete files/dirs older than 10 days 
$ find . -mtime +10 -exec rm {} \;

12. To compress file modified in last 10 days
$ find . -mtime -10 -exec compress –r {} \;

13. To remove file modified exectly 10 days back
$ find . -mtime 10 -exec rm {} \;

14. Search files with 777 permissions
$ find . -perm 777 –print

15. Search using incasesensitive string for file/dirname (use option i with name)
$ find . –iname "error" –print

16. Search files in current directory and not in subdirectory
$ find . -maxdepth 1 -type f -newer first_file

17. Search files with extension txt & remove those interactively(system will ask whether you want to delete file or not)
$ find $HOME/. -name *.txt -ok rm {} \;

18. Search links pointing to nothing using perl.
$ find / -type l -print | perl -nle '-e || print';

1 comment: