1. Searching for files
-
We can make a quick search for files with
locate:locate bin/zipIf the search requirement is not so simple, we can combine
locatewith other tools, likegrep:locate zip | grep binlocate zip | grep bin | grep -v unzip -
While
locatesearches are based only on the file name, withfindwe can also make searches based on other attributes of files.It takes as arguments one or more directories that are to be searched:
ls -aR ~find ~To find only directories we can use the option
-type dand to find only files we can use-type f:find . -type dfind . -type ffind . -type d | wc -lfind . -type f | wc -lfind . | wc -l -
We can also search by filename and file size:
sudo find /etc -type f | wc -lsudo find /etc -type f -name "*.conf" | wc -lWe enclose the search pattern in double quotes to prevent shell from expanding "
*".sudo find /etc -type f -name "*.conf" -size -2k | wc -lsudo find /etc -type f -name "*.conf" -size 2k | wc -lsudo find /etc -type f -name "*.conf" -size +2k | wc -l-2kmatches the files whose size is less than 2 Kilobytes,2kthose who are exactly 2 Kilobytes, and+2kthose who are more than 2 Kilobytes. Besideskwe can also useMfor Megabytes,Gfor Gigabytes, etc. -
findsupports many other tests on files and directories, like the time of creation or modification, the ownership, permissions, etc. These tests can be combined with logical operators to create more complex logical relationships. For example:find ~ \( -type f -not -perm 0600 \) -or \( -type d -not -perm 0700 \)This looks weird, but if we try to translate it to a more understandable language it means: find on home directory ( files with bad permissions ) -or ( directories with bad permissions ). We have to escape the parentheses to prevent shell from interpreting them.
-
We can also do some actions on the files that are found. The default action is to
-printthem to the screen, but we can also-deletethem:touch test{1,2,3}.baklsfind . -type f -name '*.bak' -deletelstouch test{1,2,3}.bakfind . -type f -name '*.bak' -print -deletelsWe can also execute custom actions with
-exec:touch test{1,2,3}.baklsfind . -name '*.bak' -exec rm '{}' ';'lsHere
{}represents the pathname that is found and;is required to indicate the end of the command. Both of them have been quoted to prevent shell from interpreting them.If we use
-okinstead of-execthen each command will be confirmed before being executed:touch test{1,2,3}.baklsfind . -name '*.bak' -ok rm '{}' ';' -
Another way to perform actions on the results of
findis to pipe them toxargs, like this:touch test{1,2,3}.baklsfind . -name '*.bak' | xargs echofind . -name '*.bak' | xargs ls -lfind . -name '*.bak' | xargs rmlsxargsgets input from stdin and converts it into an argument list for the given command.