Linux in find Common usage examples

·find   path   -option   [   -print ]   [ -exec   -ok   command ]   {} \;

find Arguments to the command ;

pathname: find Directory path found by command . For example . To represent the current directory , use / To represent the system root .
-print: find Command to export matching files to standard output .
-exec: find Command to execute the shell command . The form of the corresponding command is 'command' { } \;, Be careful { } and \; Space between .
-ok: and -exec It's the same thing , Only in a more secure mode shell command , Before each command is executed , Will give a hint , Let the user decide whether to execute .

#-print Output the found file to standard output
#-exec   command   {} \;      —– Execute the found file command operation ,{} and \; There's a space between
#-ok and -exec identical , Just ask the user before operation

example :find . -name .svn | xargs rm -rf

====================================================

-name   filename             # Search name is filename The file of
-perm                        # Find by execution permission
-user    username             # Find by file owner
-group groupname            # Find by group
-mtime   -n +n                # Find files by file change time ,-n finger n Within days ,+n finger n Before the day
-atime    -n +n               # Check by file access time GIN: 0px">

-ctime    -n +n              # Find files by file creation time ,-n finger n Within days ,+n finger n Before the day

-nogroup                     # Check no valid group file , That is, the document's group is located in /etc/groups Does not exist in the
-nouser                     # Check no valid owner file , That is, the owner of the document /etc/passwd Do not exist in China
-newer   f1 !f2              Find file ,-n finger n Within days ,+n finger n Before the day  
-ctime    -n +n               # Find files by file creation time ,-n finger n Within days ,+n finger n Before the day  
-nogroup                     # Check no valid group file , That is, the document's group is located in /etc/groups Does not exist in the
-nouser                      # Check no valid owner file , That is, the owner of the document /etc/passwd Do not exist in China
-newer   f1 !f2               # Check the change time ratio f1 New than f2 Old documents
-type    b/d/c/p/l/f         # Check the equipment 、 Catalog 、 Character device 、 The Conduit 、 A symbolic link 、 Ordinary documents
-size      n[c]               # Check length is n block [ or n byte ] The file of
-depth                       # Make the search complete this directory before entering the subdirectory
-fstype                     # Check the change time ratio f1 New than f2 Old documents
-type    b/d/c/p/l/f         # Check the equipment 、 Catalog 、 Character device 、 The Conduit 、 A symbolic link 、 Ordinary documents
-size      n[c]               # Check length is n block [ or n byte ] The file of
-depth                       # Make the search complete this directory before entering the subdirectory
-fstype                      # Look up files in a type of file system , These file system types are usually stay /etc/fstab Find
-mount                       # Do not cross file system when checking files mount spot
-follow                      # If you encounter a symbolic link file , The file referred to in the tracking link
-cpio                %;      # Look up files in a type of file system , These file system types are usually stay /etc/fstab Find
-mount                       # Do not cross file system when checking files mount spot
-follow                      # If you encounter a symbolic link file , The file referred to in the tracking link
-cpio                        # Use for matching files cpio command , Back them up to tape devices
-prune                       # Ignore a directory

=====================================================
$find   ~   -name   "*.txt"   -print    # stay $HOME Intermediate investigation .txt File and display
$find   .    -name   "*.txt"   -print
$find   .    -name   "[A-Z]*"   -print   # Look up files that start with uppercase letters
$find   /etc   -name   "host*"   -print # Check with host Opening file
$find   .   -name   "[a-z][a-z][0–9][0–9].txt"    -print   # Look up those starting with two lowercase letters and two numbers txt file
$find .   -perm   755   -print
$find   .   -perm -007   -exec ls -l {} \;   # Check that the files that all users can read and write are the same as -perm 777
$find   . -type d   -print
$find   .   !   -type   d   -print 
$find   .   -type l   -print

$find   .   -size   +1000000c   -print        # Check length is greater than 1Mb The file of
$find   .   -size   100c         -print       # Check length is 100c The file of
$find   .   -size   +10   -print              # Check if the length exceeds the expiration date 10 Block file (1 block =512 byte )

$cd /
$find   etc   home   apps    -depth   -print   | cpio   -ivcdC65536   -o   /dev/rmt0
$find   /etc -name "passwd*"   -exec grep   "cnscn"   {}   \;   # See if it exists cnscn user
$find . -name "yao*"   | xargs file
$find   . -name "yao*"   |   xargs   echo    "" > /tmp/core.log
$find   . -name "yao*"   | xargs   chmod   o-w

======================================================

find   -name april*                     Find in the current directory to april Start file
find   -name   april*   fprint file        Find in the current directory to april Start file , And output the result to file in
find   -name ap* -o -name may*   Looking to ap or may Opening file
find   /mnt   -name tom.txt   -ftype vfat   stay /mnt The next search name is tom.txt And the file system type is vfat The file of
find   /mnt   -name t.txt ! -ftype vfat   stay /mnt The next search name is tom.txt And the file system type is not vfat The file of
find   /tmp   -name wa* -type l            stay /tmp The following search name is wa Files with symbolic links at the beginning
find   /home   -mtime   -2                 stay /home Look up the changed documents in the last two days
find /home    -atime -1                  check 1 Files accessed in days
find /home -mmin    +60                  stay /home Next investigation 60 Files changed minutes ago
find /home   -amin   +30                  Check the latest 30 Files accessed minutes ago
find /home   -newer   tmp.txt             stay /home Down check update time ratio tmp.txt Near file or directory
find /home   -anewer   tmp.txt            stay /home Down lookup access time ratio tmp.txt Near file or directory
find   /home   -used   -2                  List files or directories that have been changed , stay 2 Files or directories accessed in the day
find   /home   -user cnscn                List /home Users in the directory cnscn Files or directories for
find   /home   -uid   +501                  List /home The ID of the user in the directory is greater than 501 Files or directories for
find   /home   -group   cnscn              List /home Internal group cnscn Files or directories for
find   /home   -gid 501                   List /home Internal group id by 501 Files or directories for
find   /home   -nouser                    List /home Files or directories within that do not belong to local users
find   /home   -nogroup                   List /home Files or directories within that do not belong to the local group
find   /home    -name tmp.txt    -maxdepth   4   List /home Internal tmp.txt The maximum depth is 3 layer
find   /home   -name tmp.txt   -mindepth   3   From 2 Layer start checking
find   /home   -empty                     Find size is 0 File or empty directory of
find   /home   -size   +512k                Check larger than 512k The file of
find   /home   -size   -512k               Check less than 512k The file of
find   /home   -links   +2                Check that the number of hard connections is greater than 2 Files or directories for
find   /home   -perm   0700                Check permissions for 700 Files or directories for
find   /tmp   -name tmp.txt   -exec cat {} \;
find   /tmp   -name   tmp.txt   -ok   rm {} \;

find    /   -amin    -10     # Find last in system 10 Files accessed in minutes
find    /   -atime   -2        # Find last in system 48 Files accessed in hours
find    /   -empty             # Find files or folders that are empty in the system
find    /   -group   cat        # Find in system belongs to groupcat The file of
find    /   -mmin   -5         # Find last in system 5 Files modified in minutes
find    /   -mtime   -1       # Find last in system 24 Documents modified in hours
find    /   -nouser           # Search for invalid user files in the system
find    /   -user    fred     # Find in system belongs to FRED This user's file

Check all common files in the current directory


# find . -type f -exec ls -l {} \; 
-rw-r–r–    1 root      root         34928 2003-02-25   ./conf/httpd.conf 
-rw-r–r–    1 root      root         12959 2003-02-25   ./conf/magic 
-rw-r–r–    1 root      root          180 2003-02-25   ./conf.d/README 
Check all common files in the current directory , And in - e x e c Use... In the options ls -l The command lists them

=================================================
stay / l o g s Find the change time in 5 Previous files and delete them :
$ find logs -type f -mtime +5 -exec   -ok   rm {} \;

=================================================
Query the modified documents of the day
[[email protected] class]# find   ./   -mtime   -1   -type f   -exec   ls -l   {} \;

=================================================
Query the file and ask if you want to display
[[email protected] class]# find   ./   -mtime   -1   -type f   -ok   ls -l   {} \;  
< ls … ./classDB.inc.php > ? y
-rw-r–r–    1 cnscn    cnscn       13709   1 month 12 12:22 ./classDB.inc.php
[[email protected] class]# find   ./   -mtime   -1   -type f   -ok   ls -l   {} \;  
< ls … ./classDB.inc.php > ? n
[[email protected] class]#

=================================================
Inquire and give to awk To deal with
[[email protected] class]# who   |   awk   ’{print $1"\t"$2}’
cnscn    pts/0

=================================================
awk—grep—sed

[[email protected] class]# df   -k |   awk ‘{print $1}’ |   grep   -v   ’none’ |   sed   s"/\/dev\///g"
file system
sda2
sda1
[[email protected] class]# df   -k |   awk ‘{print $1}’ |   grep   -v   ’none’
file system
/dev/sda2
/dev/sda1

1) stay /tmp Find all in *.h, And find it in these files “SYSCALL_VECTOR", Finally, print out all the contents "SYSCALL_VECTOR" The name of the file

A) find   /tmp   -name   "*.h"   | xargs   -n50   grep SYSCALL_VECTOR
B) grep   SYSCALL_VECTOR   /tmp/*.h | cut    -d’:'   -f1| uniq > filename
C) find   /tmp   -name "*.h"   -exec grep "SYSCALL_VECTOR"   {}   \; -print

2)find / -name filename -exec rm -rf {} \;
    find / -name filename -ok rm -rf {} \;

3) For example, to find a disk that is larger than 3M The file of :
find . -size +3000k -exec ls -ld {} ;

4) take find The things that come out are copied to another place
find *.c -exec cp ‘{}’ /tmp ‘;’

If there are special documents , It can be used cpio, You can also use this grammar :
find dir -name filename -print | cpio -pdv newdir

6) lookup 2004-11-30 16:36:37 Files that have been changed when
# A=`find ./ -name "*php"` |   ls -l –full-time $A 2>/dev/null | grep "2004-11-30 16:36:37"

Linux-all, Linux | No Comments »

find example

April 18th, 2006

To be in /usr/linux Find all in *.h, And find it in these files “SYSCALL_VECTOR", Finally, print out all the contents "SYSCALL_VECTOR" The name of the file , There are several ways to achieve
find /usr/linux -name "*.h" | xargs -n50 grep SYSCALL_VECTOR
grep SYSCALL_VECTOR /usr/linux/*.h | cut -d’:’ -f1 | uniq > filename
find /usr/linux -name "*.h" -exec grep "SYSCALL_VECTOR" {} \; -print

I use find / -name filename| rm -rf, You don't succeed , Why not ?
find / -name filename -exec rm -rf {} \;
find . -name filename |rm -rf Have a try {} It means the result you find out .
\; It's equivalent to “ The constitution ”, It's nothing to say , That's how it is , stay -exec You need a symbol to indicate the end of the command . Can be in man find Find the answer .
Must let rm distinguish find Result , as follows :
find / -name filename |xargs rm -rf
The reason find . -name filename |rm -rf Not through , Because rm Commands do not accept instructions from standard input
Find a file with a specific string
For example, find the current directory containing "the string you want find…" String file :
$find . -type f -exec grep “the string you want find…” {} ; -print

Start with the root directory tmpfile, Delete it as soon as you find it
find / -name "tmpfile" -exec rm {} \;

find Of perm problem
What does the following command mean ? The key is the one before the number -, I know everything else
find -name ".*" -perm -007
That's true.
find -name ".*" -perm 755
This is used to find the permission bit for 755 Hidden files
Oh , By the way, there's more , I've omitted all the orders above find Of pathname Parameters find The default is to find the current working directory ?
If I use -ok replace -exec, Then we need to add {} \; Do you ?
This is clear , Still need , because -ok It's just -exec Prompt mode of , It's just a multi-step operation , I didn't understand those sentences just now E The meaning of the article is ha-ha sorry
-007 It refers to finding all users can read 、 Write 、 Documents executed , Be careful ~~~
Interpretation ?
find -name ".*" -perm -007 and find -name ".*" -perm 777 Is there a difference ?
-007 How did it come from ?
But there's a problem
I use find . -perm -100 The current directory... Will be listed . , Why is that ?

The following is quoted by explover stay 2002/10/01 06:15am What was published :
-007 It refers to finding all users can read 、 Write 、 Documents executed , Be careful ~~~
-007 Is to find other users ( Different groups , Not the owner ) Can be read , Write , Documents executed . It doesn't have to be read and written in the same group ,- It means that the minimum authority is 007.
The following is quoted by a cabbage in 2002/10/01 10:16am What was published :
OK 了 , ha-ha
But there's a problem
I use find . -perm -100 The current directory... Will be listed . , Why is that ?
This method will not accurately find the directory . -100 It means that the permission can be run by the owner at least .
stay unix Under the system , You can have the right to execute the directory file before you can enter a directory . That's why catalog files are listed .
find . -perm -001 -print It's often a directory file .
I don't mean to use this method to find the directory , I just don't understand -100 It makes sense
And so on , Is it right? -010 It means that the authority is at least owner Is it executable in the same group ? That is to say, in fact, the 010 and - It's separate. ,- It means at least , and 010 It's really used to describe permission bits ?
So you can see Thank you

take find The things that come out are copied to another place ?
find *.c -exec cp ‘{}’ /tmp ‘;’
If there are special documents , It can be used cpio, You can also use this grammar :
find dir -name filename -print | cpio -pdv newdir

Find files in a certain size range on disk
For example, to find a disk that is larger than 3M The file of :
find . -size +3000k -exec ls -ld {} ;

How to use find Find files that have changed on a particular day ?
You can use this line of command to achieve :
A=`find ~ -print` | ls -l –full-time $A 2>/dev/null | grep "Jun 27" | grep 1998

Use find Command to find shell How to write . such as 11 Point to 12 Dot .thanks
Create a script judgetime, The contents are as follows :
ls -l $*|awk ‘{split($8,hour,":");if((hour[1]>23 || hour[1] < 1)&&hour[1]<24)print}’
Go to the directory you want to find , function
find ./ -name "*" -exec judgetime {} \;
Note that the time format is 24 hourly .
thank you , What if I want to be precise to minutes
touch -t 04241112 starttemp # Accurate to 12 minute
touch -t 04241220 endtemp # By the end of 12 spot 20
find [dir] -newer starttemp -a ! -newer endtemp -exec ls -l {} \;
newer?
That was yesterday 12:10 How about the documents ?
Every day when it's executed , Just replace it with the date and time stamp of the day ?
I don't know if he put all the 11:00~12:00 I'll find all of them , Is it only implemented once or every day ?
In this case, I guess I forgot where I put my things , I just remember it was late at night .
with reason !
It is worthy of mottled bamboo !
Not only know how to solve problems , We also know when this kind of problem occurs , To admire !
The problem arises again . When you create this file . What should have been the column of time is now written 2002, instead of 12:00.
wait until 12:00 Have you passed !

Delete a file with a specified date
find ./ -name file name -exec rm -f {} \;
example : Delete the current 30 Documents that haven't been used in days , Use the following command :
find / -atime +30 -exec rm -f {} \;
I tried to write a short paragraph myself SHELL, Also used ll ,grep, rm A few orders , It's not good to use .
In the filtered file name list, a FOR sentence , Re execution rm . Now I want to put this paragraph SHELL Expand it and let it run regularly every day n Delete the document from the previous day , Can anyone give me some hints , thank you !
One more question , For the friend mentioned above "find / -atime +30 -exec rm -f {} \;
" Method , I've tried it a few times in the early days , But it doesn't seem right , Parameters -atime n Is to find n The files that were accessed a day ago , What I don't understand is what the time reference point here is , And this n How does the sky count .
ask Topic two 、 about "ll |cut -f 1" Did I use this command wrong , I just want to take out ll File names listed in , But with cut -f Orders can't be done , I had to change to ll |cut -c 59- This way I get the file name I want ,but it’s a pool idear ! I've tried it, too awk , It's not right either , Let's see if you can give me a little reminder ,TKS SO MUCH
Question 3 、 How to change I node Date format for My current system display format is :
-rw-r—– 1 msahz01 users 2253 2002 year 2 month 2 Japan poheader.i
I want to replace this with
-rw-rw-rw- 1 house users 2193 Apr 19 2001 hkdisp.p
How to do that ?
awk It is no problem.
ll | awk ‘{print $9}’
How many days ago to delete files
find /yourpath -mtime +31 -exec rm {} \;
find /yourpath -mtime +366 -exec rm {} \;

find in , -ctime, -mtime And its -atime What's the difference

Excuse me, -ctime and -mtime What does it matter ?
If the parent directory ctime change , The file under it is ctime Will it change automatically ?
-ctime and -mtime ,-atime Where does this information exist ?

I use -mtime -1 Found a new or modified file .
But how to find out in a day mv Here are the documents ( Their time is the original time , Earlier than a day ) ?

use -newer Options .
You can start with touch A file of the time you want is as follows :
$ touch -t 08190800 test
$ ls -l test
-rw-r–r– 1 dba other 0 Aug 19 08:00 test
then
$ find . -newer test -print
.
./.sh_history
$ ls -l .sh_history
-rw——- 1 dba other 154 Aug 20 17:39 .sh_history

use touch You can write any time you want , And then use -newer ,! -newer Option to succeed .

1.ctime contain inode Time of information modification .mtime It only refers to the time when the content of the document is established or modified .
2 Can't .
3. This information should be stored in the super block of the file system .

I checked the book -ctime Refer to inode Changes ( Or a change in the state of a file ).
Excuse me, inode What information is stored ?
Did some little tests ,-mtime Change , -ctime It must be changed too .
Change the file name , -ctime It will change .
Who can answer i-node What's in store ?

vi /usr/include/sys/inode.h

Headmaster , I can't access /usr/include/sys/inode.h .
The book is as follows :
Directories contain directory entries. Each entry contains a file or subdirectory name and an index node reference number (i-node number). To increase speed and enhance use of disk space, the data in a file is stored at various locations in the computer’s memory. The i-node contains the addresses used to locate all the scattered blocks of data associated with a file. The i-node also records other information about the file including time of modification and access, access modes, number of links, file owner, and file type.
But I found that -atime Changed , -ctime It hasn't changed yet . why ?
( I'll go first cat One ASCII file , Reuse -atime -1 It works -ctime -1 Without it .)
Why don't you follow inode Information changes , ctime Just change the contradiction ?

I don't agree with the article you posted , As I mentioned ,atime,ctime,mtime It's in the super block , stay sco unix The next one is called stat Structure .(stat_32), Different systems may have different file systems .
sco Next inode The structure is as follows :

typedef struct inode
{
struct inode *i_forw; /* inode hash chain */
struct inode *i_back; /* ‘’ */
struct inode *av_forw; /* freelist chain */
struct inode *av_back; /* ‘’ */
int *i_fsptr; /* "typeless" pointer to fs dependent */
ino32_t i_number; /* i number, 1-to-1 with dev address */
ushort i_ftype; /* file type = IFDIR, IFREG, etc. */
short i_fstyp; /* File system type */
off_t i_size; /* size of file */
ushort i_uid; /* owner */
ushort i_gid; /* group of owner */
ushort i_flag;
ushort i_want; /* i_flag extension to avoid MP races */
ushort i_count; /* reference count */
short i_nlink; /* directory entries */
dev_t i_rdev; /* Raw device number */
#define i_namtype i_rdev /* i_ftype==IFNAM subtype */
dev_t i_dev; /* device where inode resides */
struct mount *i_mton;/* ptr to mount table entry that */
/* this directory is mounted on */
struct region *i_rp; /* ptr to shared region if any */
struct stdata *i_sp; /* ptr to associated stream */
struct iisem *isem; /* ptr to XENIX semaphores */
struct iisd *isd; /* ptr to XENIX shared data */
} i_un;
#define i_mnton i_un.i_mton /* i_ftype==IFDIR IMOUNT */
#define i_rptr i_un.i_rp /* i_ftype==IFREG || i_ftype==IFBLK */
#define i_sptr i_un.i_sp /* i_ftype==IFCHR || i_ftype==IFIFO */
#define i_sem i_un.isem /* i_ftype==IFNAM && i_namtype==IFSEM */
#define i_sd i_un.isd /* i_ftype==IFNAM && i_namtype==IFSHD */

struct fstypsw *i_fstypp; /* ptr to file system switch FSPTR */
long *i_filocks; /* pointer to filock (structure) list */
unsigned long i_mappages; /* number of pages currently cached */
unsigned long i_vcode; /* read-ahead block save (NFS) */
short i_wcnt; /* write open count or ITEXT count */
struct lockb i_cilock; /* tas to synchronize i_flag changes */
ushort i_rdlocks; /* count of non-exclusive lockers */
} inode_t;

therefore , Access to a file cannot be changed inode Information .
Use chown, chgrp, chmod Commands can be a good comparison mtime and ctime
chown Change the owner of a file , use ctime Can find , use mtime I can't find .
Give it a try .

Thank you very much ! I was in Solaris On the interview . I am right -ctime Don't understand .
The results are as follows :
Modify file ,-mtime Changed , -ctime It will change .
access files ,-atime Changed , -ctime It hasn't changed .
chown, chgrp, chmod,mv, Will make -ctime change , But it doesn't affect -atime and -mtime.
touch It can be changed -mtime and/or -atime, but touch -a Only change the visit time ,-ctime Also changed .
touch -m When changing the time ,-ctime Of course, it's also changed .
It seems that there are many other things that can make -ctime change , I don't know .
Is there any way to show -mtime,atime,ctime Do you ?
It can be used -ctime To realize the backup or transfer Do you ?
Thank you very much !

There are no tools to show ,( Maybe I don't know )
Put the following program in st_mtime Switch to st_ctime, or st_atime You can get what you want .
#include
int
main (int argc, char **argv)
{
struct stat buf;
char date[80];
char fname[80];
printf("Enter filename (with full path) to check mtime : ");
scanf("%s",fname);
stat(fname, &buf);
printf ("mtime (in sec) of %s = %ld\n", fname, buf.st_mtime);
strcpy(date, ctime((time_t *)&(buf.st_mtime)));
printf ("mtime (in date) of %s = %s\n", fname, date);
}

As for file backup , What can't be ?

mtime ls -l The last time the contents of the file were modified
atime ls -lu The last time the file was accessed
ctime ls -li The status of recent file changes , Such as file modification , attribute \ Belong to change , node , Link changes, etc , It should be not rigidly, just the change before and after time

I saw ls With the help of the , I thought it was just a press ctime or atime Sort , The time shown is still mtime.

A careful comparison ,ayhan Said is right . thank you ayhan.

Thank you very much ahyan Tips ! I am here Solaris I've tried the following :
mtime use ls -l notice
atime use ls -lu notice
ctime use ls -lc notice . (ls -li Only inode number)
The book is as follows :
-c Uses time of last modification of the i-node (file
created, mode changed, and so forth) for sorting (-t)
or printing (-l or -n).
-u Uses time of last access instead of last modification
for sorting (with the -t option) or printing (with the
-l option).
-i For each file, prints the i-node number in the first
column of the report.