Читать книгу Linux Bible - Christopher Negus - Страница 168

Finding files and executing commands

Оглавление

One of the most powerful features of the find command is the capability to execute commands on any files that you find. With the -exec option, the command you use is executed on every file found, without stopping to ask if that's okay. The -ok option stops at each matched file and asks whether you want to run the command on it.

The advantage of using -ok is that, if you are doing something destructive, you can make sure that you okay each file individually before the command is run on it. The syntax for using -exec and -ok is the same:

 $ find [options] -exec command {} \; $ find [options] -ok command {} \;

With -exec or -ok, you run find with any options you like in order to find the files you are seeking. Then you enter the -exec or -ok option followed by the command you want to run on each file. The set of curly braces indicates where on the command line to read in each file that is found. Each file can be included in the command line multiple times if you like. To end the line, you need to add a backslash and semicolon (\;). Here are some examples:

 This command finds any file named passwd under the /etc directory and includes that name in the output of an echo command: $ find /etc -iname passwd -exec echo "I found {}" \; I found /etc/pam.d/passwd I found /etc/passwd

 The following command finds every file under the /usr/share directory that is more than 5MB in size. Then it lists the size of each file with the du command. The output of find is then sorted by size, from largest to smallest. With -exec entered, all entries found are processed, without prompting: $ find /usr/share -size +5M -exec du {} \; | sort -nr 116932 /usr/share/icons/HighContrast/icon-theme.cache 69048 /usr/share/icons/gnome/icon-theme.cache 20564 /usr/share/fonts/cjkuni-uming/uming.ttc

 The -ok option enables you to choose, one at a time, whether each file found is acted upon by the command you enter. For example, you want to find all files that belong to joe in the /var/allusers directory (and its subdirectories) and move them to the /tmp/joe directory: # find /var/allusers/ -user joe -ok mv {} /tmp/joe/ \; < mv … /var/allusers/dict.dat> ? y < mv … /var/allusers/five> ? y

Notice in the preceding code that you are prompted for each file that is found before it is moved to the /tmp/joe directory. You would simply type y and press Enter at each line to move the file, or just press Enter to skip it.

For more information on the find command, enter man find.

Linux Bible

Подняться наверх