Tuesday, June 9, 2015

Find with -exec option

Difference between {} \; and {} \+ and | xargs

Below 3 commands run and output same result but the first command takes a little time and the format is also little different.

find . -type f -exec file {} \;
find . -type f -exec file {} \+
find . -type f | xargs file

It's because 1st one runs the file command for every file coming from the find command. So, basically it runs as:

file file1.txt
file file2.txt

But latter 2 find with -exec commands run file command once for all files like below:

file file1.txt file2.txt

Following command will move found files to another location.

find . -type f -iname '*.cpp' -exec mv {} ./test/ \;

To find the files in the current directory that contain the text "chrome"

find . -exec grep chrome {} \;

Delete Files Older Than x Days on Linux

find /path/to/files* -mtime +5 -exec rm {} \;

find /path/to/files* -mtime +5 -exec ls -lrt {} \;

cd /var/tmp && find stuff -mtime +90 -exec /bin/rm {} \+

Note that there are spaces between rm, {}, and \;

  • -mtime +60 means you are looking for a file modified 60 days ago.
  • -mtime -60 means less than 60 days.
  • -mtime 60 If you skip + or - it means exactly 60 days.
Display content of file on screen that were last modified 60 days ago, use
$ find /home/you -iname "*.txt" -mtime -60 -exec cat {} \;
Count total number of files using wc command
$ find /home/you -iname "*.txt" -mtime -60 | wc -l
You can also use access time to find out pdf files. Following command will print the list of all pdf file that were accessed in exactly last 60th  day,
$ find /home/you -iname "*.pdf" -mtime 60 -print
Print the file names which contains bills:

find . -name '*bills*' -print

this prints all the files

./may/batch_bills_123.log
./april/batch_bills_456.log

List the files based on the size

ls -lS /path/to/folder/

Capital S.

This will sort files in size

To exclude directories:

ls -lS | grep -v '^d'

List only regular files 

ls -lS | grep '^-'

Filter with specified size:

find . -type f -size +100k | grep '.txt.'

find . -type f -size +100k | grep '.png\|.jpg'

The above could also be rewritten as

find . -type f -size +100k -name "*.png" -o -name "*.jpg"

To list all files over 20MB in the current directory 

find . -size +20M

To get top 10 largest files:

ls -halt |head



No comments:

Post a Comment