Monday, December 2, 2013

find with -exec or xargs

The most basic thing about  find combined with -exec or xargs.


Basically, find finds a list of something and sends them to a command and let
the command to deal with them. The point I'm trying to make here is to show you that when find sends these something to a command, it can send them one at a time or all of them at a time. When it does one at a time, it's less efficient but it's safer and more flexible. In the opposite side, when it sends something all at a time, it's more efficient but less flexible.

Say you have three files: a1,  a2 and a3


#1.  \; sends parameters to the command following -exec one at a time.
$ find . -type f -name "a*" -exec echo '{}' \;
./a1   -- '{}' represents each of one of them each time echo runs.
./a2
./a3


#2.  Both + in -exec and xargs: collects the filenames into groups or sets, and runs the command once per set
$ find . -type f -name "a*" -exec echo '{}' +
./a1 ./a2 ./a3
$ find . -type f -name "a*" | xargs     
./a1 ./a2 ./a3

Summary: 
1. -exec normally sends parameters found to command line one at a time with \; at end
2. -exec can also combine parameters into one line and send it as a whole to command line with + at end, similar to xargs does.
3. We can add extra parameters to command line when using -exec with \;. However, you are not able to do so using -exec using +, same goes to using xargs.The combined one line parameter is all you got to send to command line when using xargs or -exec with +.
4. -exec with +   is kind of equal to   xargs

For example, ~/ is an extra parameter.
find . -type f -exec cp '{}'  ~/  \;    
find . -type f -exec cp '{}'  ~/ +      # not working
find . -type f  | xargs cp ~/              # not working

Useful tips:
$ find . -type f   -mmin  -30   # files modified less than 30mins ago.  
$ find . -type f   -mtime  -3    # files modified less than 3 days ago.

No comments:

Post a Comment