find
Updated: September 28, 2024
Find is one of the most powerful tools when used correctly. It can be used to parse over many objects and files all the while making changes. Much more than just finding files. However, it is not used for searching inside a file, use egrep for that!
FILTER EXAMPLES
find . -type f -name "somefile.txt" # finds files within current directory
-iname # will do case insensitive search
-type d # directories
find . -type f -mmin -10 # find files modified in the last 10m
-mmin +10 # find files modified more than 10m ago
-mtime -20 +5 # find files modified between 5-20 days ago
-amin -atime # access minutes | days
-ctime # changed min | days
-size +5M # 5k=kilobytes | G=gigabytes
-empty # empty files
-perm 755 # search files by permission
ACTION EXAMPLES
find some_dir -exec chown user:group {} + # megacron:underlings
# {} = placeholder for name since we are using find command (not giving a name)
# + or \; is to end the -exec command
find some_dir -type d -exec chmod 775 {} + # recursivly change perm on all dir in dir
find some_dir -type d -exec chmod 775 {} + # recursivly change perm on all files in dir
find . -type f -name "*.jpg" # always run find command before using rm like this
-maxdepth 1 # sets so find will not tunnel down subdirectories
find . -type f -name "*.jpg" -maxdepth 1 -exec rm {} + # removes all jpg files of current directory
find . \( -size +8k -o -size 8k \) ! -name "TekThing*.txt" # backslash keeps () symbols from being in search
find . ! \( -size +8k -o -size 8k \) -name "TekThing*.txt" # tekthing that is <8k
# rename files
sudo find . -name "*.txt" -exec rename 's/txt/TXT/g' {} \; # s=substitute g-globally on the computer.
sudo find . -name "*.jpg" -exec rename 'y/A-Z/a-z/' {} + # rename files from upper to lower case
find . -type f -name ".*" -exec rename 's/^\.//' {} + # remove leading . ie make unhidden
for file in .[^.]*; do mv "$file" "${file#.}"; done # remove leading . ie make unhidden if rename cmd doesn't work
rename 's/ //' *.jpg # removes any spaces in a name
rename 's/ /_/' *.jpg # convert spaces to underscore
# print to a file
find . -name "*.txt" -fprint testfile.txt
find . -name "*.txt" > testfile.txt
# sort
find . -type d | sort
# find by user
find . -user megacron # find all files owned by that user