OnWorks Linux and Windows Online WorkStations

Logo

Free Hosting Online for WorkStations

< Previous | Contents | Next >

Improving Efficiency

When the -exec action is used, it launches a new instance of the specified command each time a matching file is found. There are times when we might prefer to combine all of the search results and launch a single instance of the command. For example, rather than executing the commands like this:

ls -l file1

ls -l file2

we may prefer to execute them this way:

ls -l file1 file2

thus causing the command to be executed only one time rather than multiple times. There are two ways we can do this. The traditional way, using the external command xargs and the alternate way, using a new feature in find itself. We’ll talk about the alternate way first.

By changing the trailing semicolon character to a plus sign, we activate the ability of find to combine the results of the search into an argument list for a single execution of the desired command. Going back to our example, this:


find ~ -type f -name 'foo*' -exec ls -l '{}' ';'

find ~ -type f -name 'foo*' -exec ls -l '{}' ';'


-rwxr-xr-x 1 me

-rw-r--r-- 1 me

-rwxr-xr-x 1 me

-rw-r--r-- 1 me


image

me 224 2007-10-29 18:44 /home/me/bin/foo

me 224 2007-10-29 18:44 /home/me/bin/foo

me

me

0 2016-09-19 12:53 /home/me/foo.txt

0 2016-09-19 12:53 /home/me/foo.txt

will execute ls each time a matching file is found. By changing the command to:



find ~ -type f -name 'foo*' -exec ls -l '{}' +

find ~ -type f -name 'foo*' -exec ls -l '{}' +


-rwxr-xr-x 1 me

-rw-r--r-- 1 me

-rwxr-xr-x 1 me

-rw-r--r-- 1 me


image

me 224 2007-10-29 18:44 /home/me/bin/foo

me 224 2007-10-29 18:44 /home/me/bin/foo

me

me

0 2016-09-19 12:53 /home/me/foo.txt

0 2016-09-19 12:53 /home/me/foo.txt

we get the same results, but the system only has to execute the ls command once.


Top OS Cloud Computing at OnWorks: