Linux - Find command cheatsheet

By xngo on June 27, 2019

# Official manual: https://www.gnu.org/software/findutils/manual/html_mono/find.html
 
# A single sed command for each file found is executed.
    find . -type f -name '*.txt' -exec sed -i 's/SEARCH/REPLACE/g' {} \;
 
# All files found are given as parameters to sed at once.
    find . -type f -name '*.txt' -exec sed -i 's/SEARCH/REPLACE/g' {} +
 
# Find and execute multiple commands.
    find /usr/local/bin/ -name '*.sh' -type f -execdir echo "Executing {}" \; -execdir chmod +x {} \; 
 
# Find and execute multiple commands with success condition.
    find "${base_dir}" -type f -name '*.url' -exec grep "${search_term}" {} \; -exec echo {} \;
 
# Find multiple filename patterns.
    find . -type f -o -iname '*.asf' -o -iname '*.avi'
 
# Find files with size 0, greater than 1MB, greater than 500K.
    find . -type f -size 0
    find . -type f -size +1M
    du -d 0 -t 500K -h /bin/*
 
# Find empty directories.
    find . -type d -empty
 
# Find directories of this directory only.
    find . -maxdepth 1 -mindepth 1 -type d
 
# Find all images from current directory. Very slow because it reads the file content.
    find . -type f -exec file {} \; | grep -o -P '^.+: \w+ image'
 
# Find and delete file marked as *.xmp.
    find . -type f -name '*.xmp' | sed 's/\.xmp//' | tr '\n' '\0' | xargs -0 rm -f "{}"
 
# Find and print size. For printf format, see http://man7.org/linux/man-pages/man1/find.1.html
    find . -type f -name 'all.txt' -printf '%s %p\n' | numfmt --field=1 --to=iec-i  --format='%10.3f'
    find . -type f -name 'all.txt' -printf '%s %k %p\n' 

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.