• LINUX > rechercher des fichiers

      GÉNÉRALITÉS

      find chemin critère(s) action

       

      chemin peut être . pour le chemin courant, $HOME pour le répertoire de l’utilisateur ou de la forme /le/chemin

      PAR DATE

      +n plus grand que n

      -n plus petit que n

      n exactement n

       

      Fichiers 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

      -empty File is empty and is either a regular file or a directory.

       

      -fstype type File is on a filesystem of type type.

       

      -gid n File’s numeric group ID is n.

       

      -type x Fichier de type x :

      b block spécial

      c caractère spécial

      d répertoire

      p named pipe (FIFO)

      f fichier normal

      l lien symbolique. If you want to search for symbolic links when -L is in effect, use -xtype.

      s socket

      D door (Solaris)

      Groupes et users

      Fichiers appartenant au group toto :

      find . -group toto


      Fichiers appartenant au user toto :

      find . -user toto

       

      -nouser Aucun user correspond to file’s numeric user ID

       

      -nogroup Aucun groupe correspond to file’s numeric group ID

      Permissions

      valeur octale → lecture : 4 - écriture : 2 - exécution : 1

      ordre des permissions → group user other

       

      Fichiers 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 (-444 ou -a+r), have at least on write bit set ( /222 ou /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 mode File’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 -mode All of the permission bits mode are set for the file.

       

      -perm /mode Any 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 () (-iname pour 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 pattern idem -lname, but the match is case insensitive.

       

      -inum n File has inode number n. It is normally easier to use the -samefile test instead.

       

      -ipath pattern Behaves in the same way as -iwholename. This option is deprecated, so please do not use it.

       

      -iregex pattern idem -regex, but the match is case insensitive.

       

      -iwholename pattern idem -wholename, but the match is case insensitive.

       

      -links n File has n links

       

      -lname pattern symbolic 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 .mp3 dans 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 pattern match on the whole path, not a search. Ex: chercher un fichier ./fubar3, on utilise .*bar. ou .*b.*3, mais pas ‘f.*r3′.

       

      -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links.

       

      -wholename pattern File 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 -prune rather 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.

       

      b pout 512-bits blocks (par défaut)

      c pour bits

      w pour two-byte words

      k pour Kilobits (1024 bits)

      M pour Megabits (1048576 bits)

      G for 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

      -delete effacer les fichiers

       

      find . -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 file like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched.

       

      -fprint file print 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 file like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched.

       

      -fprintf file format like -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.

       

      -print0 print 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.

       

      %a date 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

       

      %Ak File’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.

      H heure (00..23)

      k heure ( 0..23)

      I heure (01..12)

      l heure ( 1..12)

      M minute (00..59)

      p locale’s AM or PM

      r time, 12-hour (hh:mm:ss [AP]M)

      S second (00..61)

      T time, 24-hour (hh:mm:ss)

      + Date et heure au format : 2004-04-28+22:22:05. The time is given in the current timezone

      X locale’s time representation (H:M:S)

      Z time zone (e.g., EDT), or nothing if no time zone is determinable

       

      Champs DATE :

      a locale’s abbreviated weekday name (Sun..Sat)

      A locale’s full weekday name, variable length (Sunday..Saturday)

      b locale’s abbreviated month name (Jan..Dec)

      B locale’s full month name, variable length (January..December)

      c locale’s date and time (Sat Nov 04 12:02:33 EST 1989)

      d day of month (01..31)

      D date (mm/dd/yy)

      h same as b

      j day of year (001..366)

      m month (01..12)

      U week number of year with Sunday as first day of week (00..53)

      w day of week (0..6)

      W week number of year with Monday as first day of week (00..53)

      x locale’s date representation (mm/dd/yy)

      y last two digits of year (00..99)

      Y year (1970…)

       

      %b espace 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.

      %c File’s last status change time in the format returned by the C ‘ctime’ function.

      %Ck File’s last status change time in the format specified by k, which is the same as for %A.

      %d File’s depth in the directory tree; 0 means the file is a command line argument.

      %D The device number on which the file exists (the st_dev field of struct stat), in decimal.

      %f File’s name with any leading directories removed (only the last element).

      %F Type of the filesystem the file is on; this value can be used for -fstype.

      %g File’s group name, or numeric group ID if the group has no name.

      %G File’s numeric group ID.

      %h Leading directories of file’s name (all but the last element). If the file name contains no slashes (current directory) the %h specifier expands to ".".

      %H Command line argument under which file was found.

      %i File’s inode number (in decimal).

      %k espace 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.

      %l Object of symbolic link (empty string if file is not a symbolic link).

      %m File’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’).

      %M File’s permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later.

      %n Number of hard links to file.

      %p File’s name.

      %P File’s name with the name of the command line argument under which it was found removed.

      %s File’s size in bytes.

      %t File’s last modification time in the format returned by the C ‘ctime’ function.

      %Tk File’s last modification time in the format specified by k, which is the same as for %A.

      %u File’s user name, or numeric user ID if the user has no name.

      %U File’s numeric user ID.

      %y File’s type (like in ls -l), U=unknown type (shouldn’t happen)

      %Y File’s type (like %y), plus follow symlinks: L=loop, N=nonexistent

      %Z file’s security context.

       

      Un caractère % character followed by any other character is discarded (but the other character is printed).

      The %m and %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.

       

      -prune If -depth is not given, true; if the file is a directory, do not descend into it. If -depth is given, false; no effect.

       

      -quit Exit 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.

       

      -ls liste dans le format ‘ls -dils‘ :

      75615 5521 -rw-rw-r-- 1 toto toto 319705 Dec 14 12:58 ./mon_fichier.mp3

      UNUSUAL FILENAMES

      -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal.

       

      -ls, -fls Unusual 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, -fprintf If 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, -fprint Quoting 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' \) , \
      \( -size +100M -fprintf /root/big.txt '%-10s %p\n' \)

      PERFORMANCES

      Pour faire des actions sur des fichiers de manière rapide, utiliser xarg par 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.txt est beaucoup plus rapide que grep -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 }’ fichier

      Print the first item ($1) and then the third last item $(NF-2) from each line in samplefile.txt: awk ‘{print $1, $(NF-2) }’ fichier

      Print 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"‘

 

Aucun commentaire

 

Laissez un commentaire