Shell, find it! Some examples of the find command line tool

Have you lost something? You may fall in love with the find command. GNU Find tells you where a file is, given a condition. You shall use regular expressions and parameters related to lots of file features, like last access date, last modification date, its i-node, the file format of the device where it’s being saved, etc.

The syntax is find dir1 … dirM cond1 .. condN. It will search the directory tree rooted at each diri, for i = 1 to M, all files matching conditions cond1 to condN evaluated from left to right.

Let’s see some examples:

  1. find /bin -links +1
    Searches files in /bin and its subdirectories having 1 or more hard links.
  2. find /bin -links +1 -type f
    Idem, but only matches regular files (-type f).
  3. find -size +8k -printf ‘%p %s\n’
    If no directory root is given, the default is . (the working one). This command seeks files whose size is at least 8KB and writes its name and size.
  4. find . -name core -exec rm -i {} \; -print
    Looks for files called «core» (-name core), asks for confirmation to delete them (-exec rm -i {} \;) and, after all, prints their name (-print). Notice that you can run any command with «-exec». In rm -i, -i stands for «Ask for a confirmation», and «{}» means «the file matching the conditions». «-exec» must be closed with «\;».
  5. find /usr/include -name ‘*.h’ -exec grep -H SIGCHLD {} \;
    Looks from /usr/include on all files with the extension .h (-name ‘*.h’, with quotes to avoid the shell understanding the * as a metacharacter and letting the find command use it) and having the string «SIGCHLD». That is, for each file that has matched the conditions, «grep -H SIGCHLD» is run.
  6. find -atime +1 -type f -exec mv {} TMP \;
    Moves files that haven’t been accessed today (-atime +1) to the dir called TMP, in our working directory.

Thanks FIB.

Tags: , , , , , ,

Leave a Reply


Entra