Softpanorama
May the source be with you, but remember the KISS principle ;-)

Contents Bulletin Scripting in shell and Perl Network troubleshooting History Humor

Unix find tutorial

Prev | Contents | Next

Part 10: Examples of Usage of Unix Find Command

See also Recommended Links Man pages Unix Find Tutorial

Script with examples written by Viktor Chuyko

Script started on Fri Oct  1 10:31:16 1999
hills{501}vchuyk01: cat myfind
#!/usr/bin/bash
# EWORK8
# Script:myfind 
# Written by Viktor Chuyko
#
# This program demonstrates the features of find command
#
# This script is written in the bash scripting language
#
#
#

It is great Mr. Wostner's idea to run 'date' command because the programs
seaching the entire system with find command take incredibly long time
to output the result.
I could not get the output of myfind program inside script. It took 
a number of hours.
I used another method to submit current assignment. Sorry about that.

echo
date

echo
echo "Next is listing of the files starting from home dir, that have
size 50k or less and have extention html."
find . \( -size 100 -o -size -100 \)  -name '*.html' \
   -exec  ls -l {} \;  2> /dev/null 

echo
echo "The following is the number of symbolic links starting from root:"
find /students -type l -print 2> /dev/null |wc -l   

echo
echo "Below is listing of all directories starting from root that have
sticky bit (t or T) set."

find / -type d  -perm -1000  -exec ls -ld {} \; 2> /dev/null

echo
echo "Here is creating \"junk\" directory."
find ~ -type d -exec mkdir junk {} \; 2> /dev/null
echo
ls -ld ~/junk
echo
echo "I created the following empty files in junk directory:"
echo
find ~/junk -exec touch ~/junk/cart{1,2,3,4,5,6} {} \; 2> /dev/null

find ~/junk  -name 'cart[1-6]' -exec ls -l {} \; 2> /dev/null
echo
echo "After renaming and removing some of the files from junk directory
long listing of all the files in that directory looks like:"
echo
find ~/junk  -name 'cart1' -exec mv {} ~/junk/A \; 
find ~/junk  -name 'cart2' -exec mv {} ~/junk/B \;
find ~/junk  -name 'cart3' -exec mv {} ~/junk/C \;

#ls -l ~/junk

find ~/junk  -name 'cart[4-6]' -exec rm {}  \;
find ~/junk   -name "*" -exec ls -l {} \; 
#ls -l ~/junk

echo "Following is to say good bye."
echo
date
hills{502}vchuyk01: myfind

Fri Oct  1 10:31:37 PDT 1999

Next is listing of the files starting from home dir, that have
size 50k or less and have extention html.
-rwxr-xr-x   1 vchuyk01   c73762         824 Sep 30 13:01 ./public_html/index.html
-rw-r--r--   1 vchuyk01   c73762         524 Sep 30 13:01 ./public_html/project_outline.html
-rwxr--r--   1 vchuyk01   c73762        4439 Sep 30 13:01 ./public_html/command.html
-rw-r--r--   1 vchuyk01   c73762         508 Sep 30 13:01 ./public_html/project.html
-rw-r--r--   1 vchuyk01   c73762         391 Sep 30 13:01 ./public_html/cut.html
-rw-r--r--   1 vchuyk01   c73762         335 Sep 30 13:01 ./public_html/paste.html
-rw-------   1 vchuyk01   c73762         586 Sep 30 13:01 ./public_html/lynx_bookmarks.html
-rw-------   1 vchuyk01   c73762         169 Sep 30 13:01 ./public_html/read.html
-rw-------   1 vchuyk01   c32324        1004 Sep 30 13:01 ./lynx_bookmarks.html
-rw-------   1 vchuyk01   c32324         304 Sep 30 13:01 ./project_outline.html

The following is the number of symbolic links starting from root:
144

Below is listing of all directories starting from root that have
sticky bit (t or T) set.
d-wxrw--wt   3 3395       users         2048 Aug 10  1997 /opt/video/DVC_SDK/examples/xcam
drwxrwxrwt  13 bin        bin         571392 Sep 30 21:42 /tmp
drwxrwxrwt   2 root       root          2048 Sep 30 21:43 /var/spool/cron/tmp
drwxrwsrwt   2 daemon     daemon        2048 Sep  4 09:32 /var/spool/calendar
drwxrwxrwt   6 root       bin           2048 Sep 22 22:25 /var/opt/dce/rpc/local
drwxr-xr-t   2 root       sys             96 Sep 22 22:24 /var/opt/dce/rpc/local/00475
drwxr-xr-t   3 root       root            96 Sep 22 22:25 /var/opt/dce/rpc/local/01191
drwxr-xr-t   2 root       root            96 Sep 22 22:25 /var/opt/dce/rpc/local/01191/c-3
drwxrwxrwt   2 root       sys           2048 Sep 22 22:25 /var/opt/dce/rpc/local/s-0
drwxrwxrwt   2 root       sys             96 Sep 22 22:25 /var/opt/dce/rpc/local/s-3
drwxrwxrwt   2 root       bin             96 May 30  1998 /var/opt/dce/security/creds
drwxrwxrwt   2 root       bin             96 Jun 10  1996 /var/opt/dce/svc
drwxr-xr-t   2 sabensoh   cisdept       1024 Aug 28 15:33 /pub/cis/cis110c/lab4
drwxr-xr-t   2 sabensoh   cisdept       1024 Aug 28 15:32 /pub/cis/cis110c/lab6
drwxr-xr-t   2 sabensoh   cisdept       1024 Aug 28 15:23 /pub/cis/cis110c/life1
drwxr-xr-t   2 sabensoh   cisdept       1024 Aug 28 15:24 /pub/cis/cis110c/life2
drwxr-xr-t   2 sabensoh   cisdept       1024 Aug 28 15:27 /pub/cis/cis110c/life3
drwxr-xr-t   2 sabensoh   cisdept       1024 Aug 28 15:28 /pub/cis/cis110c/lab3

Here is creating "junk" directory.

drwx--S---   2 vchuyk01   c73762        2048 Sep 30 21:37 /students/vchuyk01/junk

I created the following empty files in junk directory:

-rw-------   1 vchuyk01   c73762           0 Sep 30 21:43 /students/vchuyk01/junk/cart1
-rw-------   1 vchuyk01   c73762           0 Sep 30 21:43 /students/vchuyk01/junk/cart2
-rw-------   1 vchuyk01   c73762           0 Sep 30 21:43 /students/vchuyk01/junk/cart3
-rw-------   1 vchuyk01   c73762           0 Sep 30 21:43 /students/vchuyk01/junk/cart4
-rw-------   1 vchuyk01   c73762           0 Sep 30 21:43 /students/vchuyk01/junk/cart5
-rw-------   1 vchuyk01   c73762           0 Sep 30 21:43 /students/vchuyk01/junk/cart6

After renaming and removing some of the files from junk directory
-rw-------   1 vchuyk01   c73762           0 Sep 30 21:43 /students/vchuyk01/junk/B
-rw-------   1 vchuyk01   c73762           0 Sep 30 21:43 /students/vchuyk01/junk/C
-rw-------   1 vchuyk01   c73762           0 Sep 30 21:43 /students/vchuyk01/junk/A
Following is to say good bye.


hills{503}vchuyk01: exit
exit

script done on Fri Oct  1 10:31:47 1999

Unix-Linux find command mini-tutorial

Unix-Linux find command mini-tutorial

When specifying time with find  options such as -mmin  (minutes) or -mtime  (24 hour periods, starting from now), you can specify a number "n" to mean exactly n, "-n" to mean less than n, and "+n" to mean more than n. 2  For example:

find . -mtime 0   # find files modified within the past 24 hours
find . -mtime -1  # find files modified within the past 24 hours
find . -mtime 1   # find files modified between 24 and 48 hours ago
find . -mtime +1  # find files modified more than 48 hours ago
find . -mmin +5 -mmin -10 # find files modifed between 6 and 9 minutes ago

The following displays non-hidden (no leading dot) files in the current directory only (no subdirectopries), with an arbitrary output format (see the man page for the dozens of possibilities with the -printf action):

find . -maxdepth 1 -name '[!.]*' -printf 'Name: %16f Size: %6s\n'

As a system administrator you can use find to locate suspicious files (e.g., world writable files, files with no valid owner and/or group, SetUID files, files with unusual permissions, sizes, names, or dates).  Here's a final more complex example (which I save as a shell script):

find / -noleaf -wholename '/proc' -prune \
     -o -wholename '/sys' -prune \
     -o -wholename '/dev' -prune \
     -o -wholename '/windows-C-Drive' -prune \
     -o -perm -2 ! -type l  ! -type s \
     ! \( -type d -perm -1000 \) -print

This says to seach the whole system, skipping the directories /proc, /sys, /dev, and /windows-C-Drive (presumably a Windows partition on a dual-booted computer).  The -noleaf option tells find to not assume all remaining mounted filesystems are Unix file systems (you might have a mounted CD for instance).  The "-o" is the Boolean OR operator, and "!" is the Boolean NOT operator (applies to the following criteria).  So this criteria says to locate files that are world writable ("-perm -2") and NOT symlinks ("! -type l") and NOT sockets ("! -type s") and NOT directories with the sticky (or text) bit set ("! \( -type d -perm -1000 \)").  (Symlinks, sockets and directories with the sticky bit set are often world-writable and generally not suspicious.)

Find tutorial from grymoire.com

Find tutorial from grymoire.com

Looking for files by type

If you are only interested in files of a certain type, use the -type argument, followed by one of the following characters:

+---------------------------------------------------+
    |Character	 Meaning				|
    +---------------------------------------------------+
    |b		 Block special file (see mknode(8))	|
    |c		 Character special file (see mknode(8)) |
    |d		 Directory				|
    |f		 Plain file				|
    |p		 Named Pipe File			|
    |l		 Symbolic link				|
    |s		 Socket					|
    +---------------------------------------------------+

Unless you are a system administrator, the important types are directories, plain files, or symbolic links (i.e. types d, f, or l).

Using the -type option, another way to recursively list files is:

find . -type f -print | xargs ls -l
 

It can be difficult to keep track of all of the symbolic links in a directory. The next command will find all of the symbolic links in your home directory, and print the files your symbolic links point to.

find . -type l -print | xargs ls -ld | awk '{print $10}'

Looking for files by sizes

Find has several options that take a decimal integer. One such argument is -size. The number after this argument is the size of the files in disk blocks. Unfortunately, this is a very vague number. Earlier versions of Unix used disk blocks of 512 bytes. Newer versions allow larger block sizes, so a "block" of 512 bytes is misleading.

This confusion is aggravated when the command ls -s is used. The -s option lists the size of the file in blocks. If the command is "/usr/bin/ls," the block size is 1024 bytes. If the command is "/usr/5bin/ls," the block size is 512 bytes.

Let me confuse you some more. The following shows the two versions of ls:

% /usr/bin/ls -sl file
14 -rwxr-xr-x 1 barnett 13443 Jul 25 23:27 file
% /usr/5bin/ls -sl file
28 -rwxr-xr-x 1 barnett staff 13443 Jul 25 23:27 file
 

Can you guess what block size should be specified so that find prints this file? The correct command is:

find . -size 27 -print
 

because the actual size is between 26 and 16 blocks of 512 bytes each. As you can see, "ls -s" is not an accurate number for find. You can put a c after the number, and specify the size in bytes,

To search for files using a range of file sizes, a minus or plus sign can be specified before the number. The minus sign means "less than," and the plus sign means "greater than." This next example lists all files that are greater than 10,000 bytes, but less than 32,000 bytes:

find . -size +10000c -size -32000c -print
 

When more than one qualifier is given, both must be true.

Searching for old files

If you want to find a file that is 7 days old, use the -mtime option:
find . -mtime 7 -print
 

An alternate way is to specify a range of times:

find . -mtime +6 -mtime -8 -print
 

Mtime is the last modified time of a file. You can also think of this as the creation time of the file, as Unix does not distinguish between creation and modification. If you want to look for files that have not been used, check the access time with the -atime argument. A command to list all files that have not be read in thirty days or more is

find . -type f -atime +30 -print
 

It is difficult to find directories that have not been accessed because the find command modifies the directory's access time.

There is another time associated with each file, called the ctime, accessed with the -ctime option. This will have a more recent value if the owner, group, permission or number of links is changed, while the file itself does not. If you want to search for files with a specific number of links, use the -linksoption.

Searching for files by permission

Find can look for files with a specific permission. It uses an octal number for these permissions. The string rw-rw-r--, indicates you and members of your group have read and write permission, while the world has read only priviledge. The same permissions, when expressed as an octal number, is 664. To find all "*.o" files with the above permission, use:

find . -name *.o -perm 664 -print
 

If you want to see if you have any directories with world write permission, use:

find . -type d -perm 777 -print
 

This only matches the exact combination of permissions. If you wanted to find all directories with group write permission, there are several combinations that can match. You could list each combination, but find allows you to specify a pattern that can be bit-wise ANDed with the permissions of the file. Simply put a minus sign before the octal value. The group write permission bit is octal 20, so the following negative value:

find . -perm -20 -print
 

will match the following common permissions:

+-------------------------+
		 |Permission   Octal value |
		 +-------------------------+
		 |rwxrwxrwx    777	   |
		 |rwxrwxr-x    775	   |
		 |rw-rw-rw-    666	   |
		 |rw-rw-r--    664	   |
		 |rw-rw----    660	   |
		 +-------------------------+

If you wanted to look for files that you can execute, (i.e. shell scripts or programs), you want to match the pattern "--x------," by typing:

find . -perm -100 -print
 

When the -perm argument has a minus sign, all of the permission bits are examined, including the set user ID bits.

Owners and groups

Often you need to look for a file that has certain permissions and belonging to a certain user or group. This is done with the -user and -group search options. To find all files that are set user ID to root, use:

find . -user root -perm -4000 -print
 

To find all files that are set group ID to staff, use:

find . -group staff -perm -2000 -print
 

Instead of using a name or group in /etc/passwd or /etc/group, you can use a number:

find . -user 0 -perm -4000 -print
find . -group 10 -perm -2000 -print
 

Often, when a user leaves a site, their account is deleted, but their files are still on the computer. A system manager can use the -nouser or -nogroup to find files with an unknown user or group ID.

Find and commands

So far, after find has found a file, all it has done is printed the filename. It can do much more than that, but the syntax can get hairy. Using xargs saves you this mental effort, but it isn't always the best solution.

If you want a recursive listing, find's output can be piped into | xargs ls -l but it is more efficient to use the built in -ls option:

find . -ls
 

This is similar to the command:

find . -print | xargs ls -gilds
 

You could also use ls -R command, but that would be too easy.

 

Find and Cpio

Find also understands cpio, and supports the -cpio and -ncpio commands:
find . -depth -cpio >/dev/rmt0
find . -depth -ncpio >/dev/rmt0
 

which do the same as

find . -depth -print | cpio -oB >/dev/rmt0
find . -depth -print | cpio -ocB >/dev/rmt0

Using Find to Execute Commands

I have already discussed how to use xargs to execute commands. Find can execute commands directly. The syntax is peculiar, which is one reasons I recommend xargs. The syntax of the -exec option allows you to execute any command, including another find command. If you consider that for a moment, you realize that find needs some way to distinguish the command it's executing from its own arguments. The obvious choice is to use the same end of command character as the shell (i.e. the semicolon). Since the shell normally uses the semicolon itself, it is necessary to "escape" the character with a backslash or quotes. There is one more special argument that find treats differently: {}. These two characters are used as the variable whose name is the file find found. Don't bother re-reading that last line. An example will clarify the usage. The following is a trivial case, and uses the -exec option to mimic the "-print' option.

find . -exec echo {} ;
 

The C shell uses the characters { and }, but doesn't change {}, which is why it is not necessary to quote these characters. The semicolon must be quoted, however. Quotes can be used instead of a backslash:

find . -exec echo {} ';'
 

as both will pass the semicolon past the shell to the find command. As I said before, find can even call find. If you wanted to list every symbolic link in every directory owned by group "staff" you could execute:

find `pwd` -group staff -exec find {} -type l -print ;
 

To search for all files with group write permission, and remove the permission, you can use

find . -perm -20 -exec chmod g-w {} ;
 

or

find . -perm -20 -print | xargs chmod g-w
 

The difference between -exec and xargs are subtle. The first one will execute the program once per file, while xargs can handle several files with each process. However, xargs may have problems with files that contain embedded spaces.

Occasionally people create a strange file that they can't delete. This could be caused by accidentally creating a file with a space or some control character in the name. Find and -exec can delete this file, while xargs could not. In this case, use ls -il to list the files and i-nodes, and use the -inum option with -exec to delete the file:

find . -inum 31246 -exec rm [] ';'
 

If you wish, you can use -ok which does the same as -exec, except the program asks you first to confirm the action before executing the command. It is a good idea to be cautious when using find, because the program can make a mistake into a disaster. When in doubt, use echo as the command. Or send the output to a file and examine the file before using the file as input to xargs. This is how I discovered that find can only use one {} in the arguments to -exec. I wanted to rename some files using "-exec mv {} {}.orig" but I learned that I have to write a shell script that I told find to execute.

File comparisons

Whenever I upgraded to a new version of Unix, one common problem was making sure I maintained all of the changes made to the standard release of Unix. Previously, I did a ls -lt in each directory, and then I examined the modification date. The files that were changed has an obviously newer date that the original programs. Even so, finding every change was tedious, as there were dozens of directories to be searched.

A better solution is to create a file as the first step in upgrading. I usually call this FirstFile. Find has a -newer option that tests each file and compares the modification date to the newer file. If you then wanted to list all files in /usr that need to be saved when the operating system is upgraded, use:

find /usr -newer /usr/FirstFile -print
 

This could then be used to create a tar or cpio file that would be restored after the upgrade.

Expressions

Find allows complex expressions. To negate a test, put a ! before the option. Since the C shell interprets this command, it must be escaped. To find all files the same age or older than "FirstFile," use
find /usr ! -newer /FirstFile -print
 

The "and" function is performed by the -a option. This is not needed, as two or more options are ANDed automatically. The "or" function is done with the -o option. Parenthesis can be used to add precedence. These must also be escaped. If you wanted to print object and "a.out" files that are older than 7 days, use:

find . ( -name a.out -o -name *.o ) -print

Keeping find from going too far

The most painful aspect of a large NFS environment is avoiding the access of files on NFS servers that are down. Find is particularly sensitive to this, because it is very easy to access dozens of machines with a single command. If find tries to explore a file server that happens to be down, it will time out. It is important to understand how to prevent find from going too far.

The important option in this case is -prune. This option confuses people because it is always true. It has a side-effect that is important. If the file being looked at is a directory, it will not travel down the directory. Here is an example that lists all files in a directory but does not look at any files in subdirectories under the top level:

find * -type f -print -o -type d -prune
 

This will print all plain files and prune the search at all directories. To print files except for those in a Source Code Control Directories, use:

find . -print -o -name SCCS -prune
 

If the -o option is excluded, the SCCS directory will be printed along with the other files.

Another useful combination is using -prune with -fstype or -xdev. Fstype tests for file system types, and expects an argument like nfs or 4.2. The later refers to the file system introduced in the 4.2 release of the Berkeley Software Distribution. To limit find to files only on a local disk or disks, use the clause -fstype 4.2 -prune or -o -fstype nfs -prune. If you needed to limit the search to one particular disk partition, use -xdev, The later is very useful if you want to help a congested disk partition, and wanted to look for all files greater than 40 blocks on the current disk partition;

find . -size -40 -xdev -print

Advanced techniques for using the UNIX find command

Advanced techniques for using the UNIX find command by Bill Zimmerly

28 Mar 2006 (IBM DeveloperWorks)

Clean out temporary files

You can use find to clean directories and subdirectories of the temporary files generated during normal use, thereby saving disk space. To do so, use the following command:

$ find . \( -name a.out -o -name '*.o' -o -name 'core' \) -exec rm {} \;

File masks identifying the file types to be removed are located between the parentheses; each file mask is preceded by -name. This list can be extended to include any temporary file types you can come up with that need to be cleaned off the system. In the course of compiling and linking code, programmers and their tools generate file types like those shown in the example: a.out, *.o, and core. Other users have similar commonly generated temporary files and can edit the command accordingly, using file masks like *.tmp, *.junk, and so on. You might also find it useful to put the command into a script called clean, which you can execute whenever you need to clean a directory.

Copy a directory's contents

The find command lets you copy the entire contents of a directory while preserving the permissions, times, and ownership of every file and subdirectory. To do so, combine find and the cpio command, like this:


Listing 2. Combining the find and cpio command
 

$ cd /path/to/source/dir

$ find . | cpio -pdumv /path/to/destination/dir

The cpio command is a copy command designed to copy files into and out of a cpio or tar archive, automatically preserving permissions, times, and ownership of files and subdirectories.

List the first lines of text files

Some people use the first line of every text file as a heading or description of the file's contents. A report that lists the filenames and first line of each text file can make sifting through several hundred text files a lot easier. The following command lists the first line in every text file in your home directory in a report, ready to be examined at your leisure with the less command:

Listing 3. The less command
 

$ find $HOME/. -name *.txt -exec head -n 1 -v {} \; > report.txt

$ less < report.txt

Maintain LOG and TMP file storage spaces

To maintain LOG and TMP file storage space for applications that generate a lot of these files, you can put the following commands into a cron job that runs daily:


Listing 4. Maintaining LOG and TMP file storage spaces
 

$ find $LOGDIR -type d -mtime +0 -exec compress -r {} \;

$ find $LOGDIR -type d -mtime +5 -exec rm -f {} \;

The first command runs all the directories (-type d) found in the $LOGDIR directory wherein a file's data has been modified within the last 24 hours (-mtime +0) and compresses them (compress -r {}) to save disk space. The second command deletes them (rm -f {}) if they are more than a work-week old (-mtime +5), to increase the free space on the disk. In this way, the cron job automatically keeps the directories for a window of time that you specify.

Copy complex directory trees

If you want to copy complex directory trees from one machine to another while preserving copy permissions and the User ID and Group ID (UID and GID -- numbers used by the operating system to mark files for ownership purposes), and leaving user files alone, find and cpio once again come to the rescue:

Listing 5. Maintaining LOG and TMP file storage spaces
 

$ cd /source/directory

$ find . -depth -print | cpio -o -O /target/directory

Find links that point to nothing

To find links that point to nothing, use the perl interpreter with find, like this:

$ find / -type l -print | perl -nle '-e || print';

This command starts at the topmost directory (/) and lists all links (-type l -print) that the perl interpreter determines point to nothing (-nle '-e || print') -- see the Resources section for more information regarding this tip from the Unix Guru Universe site. You can further pipe the output through the rm -f {} functionality if you want to delete the files. Perl is, of course, one of the many powerful interpretive language tools also found in most UNIX toolkits.

Some examples of using Unix find command

Some examples of using Unix find command.

Find examples from www.wagoneers.com

find examples from www.wagoneers.com

sudo find / -type f -name *.jpg  -exec cp {} . \;

find . -type f -size +10000 -exec ls -al {} \;
find . -atime +1 -type f -exec mv {} TMP \; # mv files older then 1 day to dir TMP
find . -name "-F" -exec rm {} \;   # a script error created a file called -F
find . -exec grep -i "vds admin" {} \;
find . \! -name "*.Z" -exec compress -f {} \;
find . -type f \! -name "*.Z" \! -name ".comment" -print | tee -a /tmp/list
find . -name *.ini
find . -exec chmod 775 {} \;
find . -user xuser1 -exec chown -R user2 {} \;
find . -name ebtcom*
find . -name mkbook
find . -exec grep PW0 {} \;
find . -exec grep -i "pw0" {} \;
find . -atime +6
find . -atime +6 -exec ll | more
find . -atime +6 -exec ll | more \;
find . -atime +6 -exec ll \;
find . -atime +6 -exec ls \;
find . -atime +30 -exec ls \;
find . -atime +30 -exec ls \; | wc -l
find . -name auth*
find . -exec grep -i plotme10 {};
find . -exec grep -i plotme10 {} \;
find . -ls -exec grep 'PLOT_FORMAT 22' {} \;
find . -print -exec grep 'PLOT_FORMAT 22' {} \;
find . -print -exec grep 'PLOT_FORMAT' {} \;
find . -print -exec grep 'PLOT_FORMAT' {} \;
find ./machbook -exec chown 184 {} \;
find . \! -name '*.Z' -exec compress {} \;
find . \! -name "*.Z" -exec compress -f {} \;
find /raid/03c/ecn -xdev -type f -print
find /raid/03c/ecn -xdev -path -type f -print
find / -name .ssh* -print | tee -a ssh-stuff
find . -name "*font*"
find . -name hpmcad*
find . -name *fnt*
find . -name hp_mcad* -print
find . -grep Pld {} \;
find . -exec grep Pld {} \;
find . -exec grep Pld {} \;
find . -exec grep PENWIDTH {} \; | more
find . -name config.pro
find . -name config.pro
find /raid -type d ".local_sd_customize" -print
find /raid -type d -name ".local_sd_customize" -print
find /raid -type d -name ".local_sd_customize" -ok cp /raid/04d/MCAD-apps/I_Custom/SD_custom/site_sd_customize/user_filer_project_dirs {} \;
find /raid -type d -name ".local_sd_customize" -exec cp /raid/04d/MCAD-apps/I_Custom/SD_custom/site_sd_customize/user_filer_project_dirs {} \;
find . -name xeroxrelease
find . -exec grep xeroxrelease {} \;
find . -name xeroxrelease
find . -name xeroxrelease* -print 2>/dev/null
find . -name "*release*" 2>/dev/null
find / -name "*xerox*" 2>/dev/null
find . -exec grep -i xeroxrelease {} \;
find . -print -exec grep -i xeroxrelease {} \;
find . -print -exec grep -i xeroxrelease {} \; > xeroxrel.lis
find . -exec grep -i xeroxrel {} \;
find . -print -exec grep -i xeroxrel {} \;
find . -print -exec grep -i xeroxrel {} \; | more
find /raid/03c/inwork -xdev -type f -print >> /raid/04d/user_scripts/prt_list.tmp
find . -exec grep '31.53' {} \;
find . -ls -exec grep "31/.53" {} \; > this.lis
find . -print -exec grep "31/.53" {} \; > this.lis
find . -print -exec grep 31.53 {} \; > this.lis
find . -exec grep -i pen {} /;
find . -exec grep -i pen {} \;
find . -print -exec grep -i pen {} \; | more
find . -exec grep -i pen {} \;
find . -atime +6 -exec ll | more \;
find . -atime +6 -exec ll \;
find . -atime +6 -exec ls \;
find . -atime +30 -exec ls \;
find . -atime +30 -exec ls \; | wc -l
find . \! -name '*.Z' -exec compress -f {} \;
find . -name 'cache*' -depth -exec rm {} \;
find . -name 'cache*' -depth -print | tee -a /tmp/cachefiles
find . -name 'cache[0-9][0-9]*' -depth -print | tee -a /tmp/cachefiles
find . -name 'hp_catfile' 'hp_catlock' -depth -print | tee -a /tmp/hp.cats
find . -name 'hp_catfile' -name 'hp_catlock' -depth -print | tee -a /tmp/hp.cats
find . -name 'hp_cat*' -depth -print | tee -a /tmp/hp.cats
find . -name 'hp_cat[fl]*' -depth -print | tee -a /tmp/hp.cats
find /raid -name 'hp_cat[fl]*' -depth -print
find . \! -name '*.Z' -exec compress -f {} \;
find . -name '*' -exec compress -f {} \;
find . -xdev -name "wshp1*" -print
find . -xdev -name "wagoneer*" -print
find . -name "xcmd" -depth -print
find /usr/contrib/src -name "xcmd" -depth -print
find /raid -type d -name ".local_sd_customize" -exec ls {} \;
find /raid -type d -name ".local_sd_customize" \
   -exec cp /raid/04d/MCAD-apps/I_Custom/SD_custom/site_sd_customize/user_filer_project_dirs {} \;

 

Examples from Sun manpage

docs.sun.com man pages section 1 User Commands

Print all files  with the given extension:

find . -name "*.c" -type f -print 

find /usr/local -name "*.html" -type f -print

Print all file that exceed a certain size and were modified long ago (to clear some space):

find / -size +1000 -mtime +30 -exec ls -l {} \;

To report all files starting in the directories "/mydir1" and "/mydir2" larger than 2000 blocks (about 1000K) AND that have not been accessed in over 30 days, enter:

  find /mydir1 /mydir2 -size +2000 -atime +30 -print

Removes unnecessary files that are older than two weeks old, but doesn't descend NFS mounted file systems while searching:

find / \( -name a.out -o -name core  -o -name '#*#' \) -type f -atime +14 -exec rm -f {} \; -o -fstype nfs -prune

Fix permissions for a group of files with given extension

    find /usr/local -name "*.html" -type f -exec chmod 644 {} \;

find htdocs cgi-bin -name "*.cgi" -type f -exec chmod 755 {} \;

This command searches through the "htdocs" and "cgi-bin" directories for files that end with the extension ".cgi". When these files are found, their permission is changed to mode 755 (rwxr-xr-x). This example shows that the find command can easily search through multiple sub-directories (htdocs, cgi-bin) at one time.

SUID games (see above):

find / \( -perm -006 -o -perm -007 \) \( ! -type -l \) -ls # find all files that have wrong permission
find / \( -nogroup -o -noname \) -ls

find / \( -perm 2000 -o -perm 4000 \)  -type f -ls | diff - suidfiles.ref

To remove (with prompting) all files starting in the "/mydir" directory that have not been accessed in over 100 days, enter:

  find /mydir -atime +100 -ok rm {} \;

To show a long listing starting in "/mydir" of files not modified in over 20 days OR not accessed in over 40 days, enter:

  find /mydir \(-mtime +20 -o -atime +40\) -exec ls -l {} \;

To list and remove all regular files named "core" starting in the directory "/prog" that are larger than 500K, enter:

  find /prog -type f -size +1000 -print -name core -exec rm {} \;

How to apply a complex selection of files (-o and -a).

find /usr/src -not \( -name "*,v" -o -name ".*,v" \) '{}' \; -print

This command will search in the /usr/src directory and all sub directories. All files that are of the form '*,v' and '.*,v' are excluded. Important arguments to note are:

The above example is shows how to select all file that are not part of the RCS system. This is important when you want go through a source tree and modify all the source files... but ... you don't want to affect the RCS version control files.

How to search for a string in a selection of files (-exec grep ...).

find . -exec grep "www.athabasca" '{}' \; -print

This command will search in the current directory and all sub directories. All files that contain the string will have their path printed to standard output.

If you want to just find each file then pass it on for processing use the -q grep option. This finds the first occurrance of the search string. It then signals success to find and find continues searching for more files.

find . -exec grep -q "www.athabasca" '{}' \; -print

This command is very important for process a series of files that contain a specific string. You can then process each file appropriately. An example is find all html files with the string "www.athabascau.ca". You can then process the files with a sed script to change those occurrances of "www.athabascau.ca" with "intra.athabascau.ca".

O'Reilly - Safari Books Online - 0131018833 - HP-UX 11i System Administration Handbook and Toolkit, Second Edition

Finding Files of a Specific Type

You may want to perform a find operation to produce a list of files only and not include directories in the operation. The following find is similar to what we performed earlier, but this time it produces a list of files only. This is achieved by specifying that we are looking for type f for files:

# find /home -type f -print 

You can search for a variety of different types such as f for a file as shown in the example, b for a block special file, l for a symbolic link, and so on.

Find Empty Files and Directories

A useful test when performing a find operation is to locate empty files. The following example searches for all empty files and directories on the system with the -empty operator that is available on some UNIX variants, including Linux. This is only a partial output because it's so long:

# find / -empty -print 
 

All the files and directories listed as a result of this find operation are empty. The long listing of /auto shown as part of the example, confirms this fact. Keep in mind that -empty is not available on all UNIX variants.

Finding Files By Name, Size, and Both Name and Size

Let's perform a couple of independent finds and then combine the criteria of the finds. The finds in the following example are performed on a small, desktop system. This allows me to search the entire system for files meeting various criteria. You may be working on a much larger, more elaborate system, so use caution when searching the entire system for files. You may slow down other users for a long period of time, depending on the number of files on the system both locally and accessible over the network.

First, let's find for all files on the system ending in.c with the command below:

# find / -name *.c -print 

You can see from this find that there are many files on the system ending in.c. I included only the beginning and end of this search because the entire output would be too long.

I also ran this command and piped the output to wc, which showed 1737 files on the system ending in.c, as shown in the following example:

# find / -name *.c | wc 
   1737    1737   77044 
# 

Now we can search for all files on the system greater than 500,000 characters in size with the find command below:

# find / -size +500000c -print 

I also ran this command and piped the output to wc, which showed 215 files on the system with a size greater than 500,000 characters, as shown in the following example:

# find / -size +500000c -print | wc 
    215     215    6281 
# 

Let's now combine the two commands and see how many of the files on the system ending in.c are also greater than 500,000 characters in size:

# find / -name *.c -size +500000c -print 
/usr/src/drivers/scsi/advansys.c 
# 

Of the 1737 files on the system ending in.c and the 215 files greater than 500,000 characters in size, only one file, advansys.c, meets both criteria. There is an implied and in the previous find command. We could have explicitly specified an and; however, it is implied in the find command. The find did indeed result in files that end in.c and are greater than 500,000 characters. The upcoming find uses the or operator, which is not implied.

What if we wanted to find both files ending in.c and.o that are greater than 500000 characters in size? We could use the -o operator which would "or" the files ending in.c and.o. The following example shows this find operation:

find / -size +500000c \(  -name *.c -o -name *.a \) -print 
find / -size +500000c \(  -name *.c -o -name *.a \) -print | wc 


# find / -size +500000c \( -name *.c -o -name *.a \) -print 

The two file extensions for which we are searching are placed in parentheses. A backslash is required before the open and close parentheses because the parentheses have meaning to the shell and we want them to be used only to specify the precedence in our find command and not to be used by the shell. The result of this find shows that many files ending in.a and.c meet the criteria of greater than 500,000 characters.

Let's now pipe the output of this commnd to wc to see precisely the number of files ending in either.c or.o and have a size greater than 500,000 characters:

# find / -size +500000c \( -name *.c -o -name *.a \) -print | wc 
     39      39     982 
# 

Of the 39 files that meet the criteria, we know that 38 ended in.a because our earlier example showed that only one file ending in.c met the criteria.

Finding Files By Owner, Type, and Permissions

You can find objects on the system owned by particular users and groups. To find all of the objects owned by user "news" on the system, we would use the following command:

# find / -user news -print 

Using the -user operator we can specify either the name of the user, in this case "news", or the user identification number. The following example shows performing the same find operation using the user identification number of "news," in this case "9," instead of the name "news":

# find / -user 9 -print 

This find operation produced exactly the same results using the name "news" and the user idenfication number "9."

You can search for a variety of different types such as f for a file, as shown in the example, b for a block special file, l for a symbolic link, and so on. We could add type -d to find only directories belonging "news" as in the following command:

# find / -user news -type d -perm 775 -print 

This is another example of using the implied and of find meaning that the find will print items that are both owned by "news" and are directories only.

Let's now add a specific permission for the directories to our implied and. We'll find only objects belonging to "news" that are directories with a permission of 775 in the following example:


# find / -user news -type d -perm 775 -print

We searched for directories belonging to "news" in which both the owner and those in the group have read-write-execute permission, and others have read-execute access. This is a common type of find operation for system administrators to perform - looking for files and directories belonging to a specific user and having specific permissions.

Prev | Contents | Next




Etc

Society

Groupthink : Understanding Micromanagers and Control Freaks : Toxic Managers : BureaucraciesHarvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Two Party System as Polyarchy : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

Skeptical Finance : John Kenneth Galbraith : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotes : Oscar Wilde : Talleyrand : Somerset Maugham : War and Peace : Marcus Aurelius : Eric Hoffer : Kurt Vonnegut : Otto Von Bismarck : Winston Churchill : Napoleon Bonaparte : Ambrose Bierce : Oscar Wilde : Bernard Shaw : Mark Twain Quotes

Bulletin:

Vol 26, No.1 (January, 2013) Object-Oriented Cult : Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks: The efficient markets hypothesis : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Vol 23, No.10 (October, 2011) An observation about corporate security departments : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Haterís Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

 

The Last but not Least


Copyright © 1996-2014 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Site uses AdSense so you need to be aware of Google privacy policy. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine. This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to make a contribution, supporting hosting of this site with different providers to distribute and speed up access. Currently there are two functional mirrors: softpanorama.info (the fastest) and softpanorama.net.

Disclaimer:

The statements, views and opinions presented on this web page are those of the author and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

Version 3.62;; Last modified: July 07, 2013