-
LINUX > rechercher des fichiers
GÉNÉRALITÉS
find chemin critère(s) action
cheminpeut être.pour le chemin courant,$HOMEpour le répertoire de l’utilisateur ou de la forme/le/cheminPAR DATE
+nplus grand que n-nplus petit que nnexactement nFichiers modifiés il y a plus de 120 minutes :
find . -mmin +120
Fichiers modifiés les 30 dernières minutes :
find . -mmin -30
Fichiers accédés il y a moins de 10 minutes :
find . -amin -10
Fichiers accédés il y a moins de 2 jours :
find . -atime -2
Fichiers accédés plus récemment que toto
-anewer toto
Fichiers changés il y a au moins n minutes.
-cmin n
Fichiers changés plus récemment que toto.
-cnewer toto
Fichiers status was last changed n*24 hours ago.
-ctime n
Fichiers modifiés plus récemment que toto
-newer toto
Fichiers accédés n jours après its status was last changed
-used n
fichiers modifiés dans les dernières 24 heures :
find . -mtime 0
PAR TYPE DE FICHIER
-emptyFile is empty and is either a regular file or a directory.-fstype typeFile is on a filesystem of type type.-gid nFile’s numeric group ID is n.-type xFichier de type x :bblock spécialccaractère spécialdrépertoirepnamed pipe (FIFO)ffichier normalllien symbolique. If you want to search for symbolic links when -L is in effect, use -xtype.ssocketDdoor (Solaris)Groupes et users
Fichiers appartenant au group toto :
find . -group toto
Fichiers appartenant au user toto :
find . -user toto
-nouserAucun user correspond to file’s numeric user ID-nogroupAucun groupe correspond to file’s numeric group IDPermissions
valeur octale → lecture :
4- écriture :2- exécution :1ordre des permissions →
group user otherFichiers en lecture et écriture (
6) pour le groupe et son propriétaire, en lecture (4) pour les autres, sans se soucier si il existe ou pas une permission pour l’exécution (marchera pour les fichiers en mode 777, par exemple) :find . -perm -664
Fichiers which are writable by somebody (their owner, or their group, or anybody else).
find . -perm /222
Fichiers en écriture by either their owner or their group. The files don’t have to be writable by both the owner and group to be matched; either will do.
find . -perm /220 find . -perm /u+w,g+w find . -perm /u=w,g=w
Fichiers en écriture by both their owner and their group.
find . -perm -220 find . -perm -g+w,u+w
Fichiers en lecture pour tous (
-444ou-a+r), have at least on write bit set (/222ou/a+w) but are not executable for anybody ( /111 and /a+x respectively)find . -perm -444 -perm /222 ! -perm /111 find . -perm -a+r -perm /a+w ! -perm /a+x
-perm modeFile’s permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you might have to specify a rather complex mode string. For example ‘-perm g=w’ will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the ‘/’ or ‘-’ forms, for example ‘-perm -g=w’, which matches any file with group write permission.-perm -modeAll of the permission bits mode are set for the file.-perm /modeAny of the permission bits mode are set for the file. If no permission bits in mode are set, this test currently matches no files.PAR NOM DE FICHIER
-name pattern ()(-inamepour case insensitive)
Les métacaractères (
*,?, et[]) match a ‘.’ at the start of the base name.Pour exclure les répertoires :
-prune. Don’t forget to enclose the pattern in quotes in order to protect it from expansion by the shell.-ilname patternidem-lname, but the match is case insensitive.-inum nFile has inode number n. It is normally easier to use the-samefiletest instead.-ipath patternBehaves in the same way as -iwholename. This option is deprecated, so please do not use it.-iregex patternidem-regex, but the match is case insensitive.-iwholename patternidem -wholename, but the match is case insensitive.-links nFile has n links-lname patternsymbolic link. The metacharacters do not treat ‘/’ or ‘.’ specially. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken.Fichiers
.mp3dans le dossier courant :find . -name "*.mp3"
fichiers .doc commençant par toto :
find . -name '*.doc' -name toto*
fichiers .doc qui ne commencent pas par toto :
find . -name '*.doc' ! -name toto*
-regex patternmatch on the whole path, not a search. Ex: chercher un fichier./fubar3, on utilise.*bar.ou.*b.*3, mais pas ‘f.*r3′.-samefile nameFile refers to the same inode as name. When -L is in effect, this can include symbolic links.-wholename patternFile name matches shell pattern pattern. The metacharacters do not treat ‘/’ or ‘.’ specially;print an entry for a directory called
./src/misc(if one exists). To ignore a whole directory tree, use-prunerather than checking every file in the tree.find . -wholename './sr*sc'
skip the directory ‘src/emacs’ and all files and directories under it, and print the names of the other files found, do something like this:
find . -wholename './src/emacs' -prune -o -print
PAR TAILLE
-size n[cwbkMG]fichiers utilisant n unités d’espaces.bpout 512-bits blocks (par défaut)cpour bitswpour two-byte wordskpour Kilobits (1024 bits)Mpour Megabits (1048576 bits)Gfor Gigabits (1073741824 bits)fichiers de plus de 100Ko
find . -size +100k
fichiers entre 10Go et 20Go
find . -size +10G -size -20G
ACTIONS
Pour des actions successives, utiliser
;entre chaque actions.effacer
-deleteeffacer les fichiersfind . -name toto* -delete
autres
-exec command ;exécuter command, qui sera exécutée dans le répertoire où a lieu le script.-exec command {} +This variant of the -exec option runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of ‘{}’ is allowed within the command. The command is executed in the starting directory.-execdir command ;-execdir command {} +idem-exec, mais éxécuté depuis le subdirectory containing the matched file, which is not normally the directory in which you started find. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec option, the ‘+’ form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your $PATH environment variable does not reference the current directory; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir.-fls filelike -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched.-fprint fileprint the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names ‘’/dev/stdout'’ and ‘’/dev/stderr'’ are handled specially; they refer to the standard output and standard error output, respectively. The output file is always created, even if the predicate is never matched.-fprint0 filelike -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched.-fprintf file formatlike -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched.-ok command ;Like -exec but ask the user first (on the standard input); if the response does not start with ‘y’ or ‘Y’, do not run the command, and return false. If the command is run, its standard input is redirected from /dev/null.-okdir command ;Like -execdir but ask the user first (on the standard input); if the response does not start with ‘y’ or ‘Y’, do not run the command, and return false. If the command is run, its standard input is redirected from /dev/null.-print0print the full file name on the standard output, followed by a null character (instead of the newline character that ‘-print’ uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the ‘-0′ option of xargs.sortie standard formatée
-printf ...
NOTE : printf ne saute pas de ligne à la fin de la chaine.
\\A literal backslash (‘\’).%%A literal percent sign.%adate et heure du dernier accès au fichier :find . -used +30 -printf "%a\n" Tue Dec 15 03:19:15.0000000000 2015 Wed Dec 9 03:17:35.0000000000 2015 Fri Dec 4 09:44:07.0140899244 2015 Tue Dec 8 03:17:35.0000000000 2015
%AkFile’s last access time in the format specified by k, which is either ‘@’ or a directive for the C ‘strftime’ function.
The possible values for k are listed below;Champs HEURE :
@secondes écoulées depuis le 1er Janvier 1970 à 00:00 GMT.Hheure (00..23)kheure ( 0..23)Iheure (01..12)lheure ( 1..12)Mminute (00..59)plocale’s AM or PMrtime, 12-hour (hh:mm:ss [AP]M)Ssecond (00..61)Ttime, 24-hour (hh:mm:ss)+Date et heure au format :2004-04-28+22:22:05. The time is given in the current timezoneXlocale’s time representation (H:M:S)Ztime zone (e.g., EDT), or nothing if no time zone is determinableChamps DATE :
alocale’s abbreviated weekday name (Sun..Sat)Alocale’s full weekday name, variable length (Sunday..Saturday)blocale’s abbreviated month name (Jan..Dec)Blocale’s full month name, variable length (January..December)clocale’s date and time (Sat Nov 04 12:02:33 EST 1989)dday of month (01..31)Ddate (mm/dd/yy)hsame as bjday of year (001..366)mmonth (01..12)Uweek number of year with Sunday as first day of week (00..53)wday of week (0..6)Wweek number of year with Monday as first day of week (00..53)xlocale’s date representation (mm/dd/yy)ylast two digits of year (00..99)Yyear (1970…)%bespace disque utilisé par le fichier en 512-byte blocks. this is usually greater than%s/1024,but it can also be smaller if the file is a sparse file.%cFile’s last status change time in the format returned by the C ‘ctime’ function.%CkFile’s last status change time in the format specified by k, which is the same as for %A.%dFile’s depth in the directory tree; 0 means the file is a command line argument.%DThe device number on which the file exists (the st_dev field of struct stat), in decimal.%fFile’s name with any leading directories removed (only the last element).%FType of the filesystem the file is on; this value can be used for -fstype.%gFile’s group name, or numeric group ID if the group has no name.%GFile’s numeric group ID.%hLeading directories of file’s name (all but the last element). If the file name contains no slashes (current directory) the %h specifier expands to ".".%HCommand line argument under which file was found.%iFile’s inode number (in decimal).%kespace disque utilisé par le fichier en 1K blocks. this is usually greater than%s/1024, but it can also be smaller if the file is a sparse file.%lObject of symbolic link (empty string if file is not a symbolic link).%mFile’s permission bits (in octal). This option uses the ‘traditional’ numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file’s mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, ‘%#m’).%MFile’s permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later.%nNumber of hard links to file.%pFile’s name.%PFile’s name with the name of the command line argument under which it was found removed.%sFile’s size in bytes.%tFile’s last modification time in the format returned by the C ‘ctime’ function.%TkFile’s last modification time in the format specified by k, which is the same as for %A.%uFile’s user name, or numeric user ID if the user has no name.%UFile’s numeric user ID.%yFile’s type (like in ls -l), U=unknown type (shouldn’t happen)%YFile’s type (like %y), plus follow symlinks: L=loop, N=nonexistent%Zfile’s security context.Un caractère
%character followed by any other character is discarded (but the other character is printed).The
%mand %d directives support the # , 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The ‘-’ format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified.-pruneIf -depth is not given, true; if the file is a directory, do not descend into it. If -depth is given, false; no effect.-quitExit immediately. No child processes will be left running, but no more paths specified on the command line will be processed. For example, find /tmp/foo /tmp/bar -print -quit will print only /tmp/foo. Any command lines which have been built up with -execdir … {} + will be invoked before find exits. The exit status might not be zero, depending on whether an error has already occurred.-lsliste dans le format ‘ls -dils‘ :75615 5521 -rw-rw-r-- 1 toto toto 319705 Dec 14 12:58 ./mon_fichier.mp3
UNUSUAL FILENAMES
-print0, -fprint0Always print the exact filename, unchanged, even if the output is going to a terminal.-ls, -flsUnusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example ‘\f’, ‘\"‘). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is.-printf, -fprintfIf the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files’ owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files’ owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use ‘\0′ as a terminator than to use newline, as file names can contain white space and newline characters.-print, -fprintQuoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print.The -ok and -okdir actions print the current filename as-is. This might change in a future release.
OPERATORS
Listed in order of decreasing precedence:
( expr ) Force precedence.
! expr True if expr is false.
-not expr Same as ! expr, but not POSIX compliant.
expr1 expr2 Two expressions in a row are taken to be joined with an implied "and"; expr2 is not evaluated if expr1 is false.
expr1 -a expr2 Same as expr1 expr2.
expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant.
expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true.
expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant.
expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2.
The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files.
EXEMPLES
Fichiers matching the name Alice (case insensitive), search in the current folder (.) and all subfolders:
find . -iname "alice" -print0
List filenames matching the name Alice or ALICE (case insensitive), search in the current folder (.) only:
find . -maxdepth 1 -iname "alice" -print0
List filenames ending in .mp3, searching in the music folder and subfolders:
find . -name "*.mp3"
List files with the exact name: Sales_document.doc in ./work and subfolders:
find . -name Sales_document.doc
List all files that belong to the user Maude:
find . -user Maude -print0
List all the directory and sub-directory names:
find . -type d
List all files in those sub-directories (but not the directory names) :
find . -type f
Fichiers de type links :
find . -type l
List all files (and subdirectories) in your home directory:
find $HOME
Find all .gif files, pipe to xargs to get the size and then pipe into tail to display only the grand total:
$ find . -iname "*.gif" -print0 | xargs -0 du -ch | tail -1
fichiers commençant par toto appartenant à lui :
find . -name 'toto*' -user lui
Find files named ‘secrets’ in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces:
$ find /tmp -name secrets -type f -print | xargs /bin/rm -f
éxécuter
monAppà chaque fichier. Les{}are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though ‘;’ could have been used in that case also.find . -type f -exec monApp '{}' \;
Traverse the filesystem just once, listing setuid files and directories into /root/suid.txt and large files into /root/big.txt.
find / \( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \
PERFORMANCES
Pour faire des actions sur des fichiers de manière rapide, utiliser
xargpar les pipes.fichiers de /usr/bin qui ne sont pas documentés dans /usr/man/man1 mais ont leur source dans /usr/src :
cd /usr/bin whereis -u -M /usr/man/man1 -S /usr/src -f *
———————————————————-
fgrep -f liste.txt texte.txtest beaucoup plus rapide quegrep -f liste.txt texte.txt———————————————————————
return the fifth item ($5) from each line of the output:
ls -l | awk ‘{print $5}’Print the Row Number (NR), then a dash and space ("- ") and then the first item ($1) from each line in samplefile.txt:
awk ‘{print NR "- " $1 }’ fichierPrint the first item ($1) and then the third last item $(NF-2) from each line in samplefile.txt:
awk ‘{print $1, $(NF-2) }’ fichierPrint every line that has at least one field. This is an easy way to delete blank lines from a file (or rather, to create a new file similar to the old file but from which the blank lines have been deleted)
awk 'NF > 0' fichier
Running
awk ‘$6 == "Dec"‘$6 matches the exact field (column 6 = Month) only the December file:ls -l /tmp/demo | awk ‘$6 == "Dec"‘