Skip to content

Instantly share code, notes, and snippets.

@loftwah
Created August 27, 2021 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loftwah/a6cbf8056dbc278854796c08bb58ced5 to your computer and use it in GitHub Desktop.
Save loftwah/a6cbf8056dbc278854796c08bb58ced5 to your computer and use it in GitHub Desktop.
Find commands I like

Find commands that give me a bit of a stiffy

These are the find commands that I use regularly.

Search for and delete empty directories.

find . -type d -empty -exec rmdir {} \;

A far more efficient approach to the above. If no path is provided, then the current working directory (CWD) is assumed, making the . superfluous.

find -type d -empty -delete

Find all files in the current directory and modify their permissions.

find . -type f -exec chmod 644 {} \;

Find files with extension .png, then rename their extension to .jpg. It's highly important that \; is used here, instead of \+, otherwise it'd make a right mess of the files, due to the way in which mv(1) works.

find . -type f -iname '*.png' -exec bash -c 'mv "$0" "${0%.*}.jpg"' {} \;

To find directories:

find . -type d

To find files by case-insensitive extension (ex: .jpg, .JPG, .jpG):

find . -iname "*.jpg"

# To find files with extension '.txt' and remove them:

find ./path/ -name '*.txt' -exec rm '{}' \;

To find files with extension '.txt' and look for a string into them:

find ./path/ -name '*.txt' | xargs grep 'string'

To find files with size bigger than 5 Mebibyte and sort them by size:

find . -size +5M -type f -print0 | xargs -0 ls -Ssh | sort -z

To find files bigger than 2 Megabyte and list them:

find . -type f -size +200000000c -exec ls -lh {} \; | awk '{ print $9 ": " $5 }'

To find files modified more than 7 days ago and list file information:

find . -type f -mtime +7d -ls

To find symlinks owned by a user and list file information:

find . -type l -user <username-or-userid> -ls

To search for directories named build at a max depth of 2 directories:

find . -maxdepth 2 -name build -type d

To search all files who are not in .git directory:

find . ! -iwholename '*.git*' -type f

Find files by matching multiple patterns:

find root_path -name '*pattern_1*' -or -name '*pattern_2*'

Find files matching a path pattern:

find root_path -path '**/lib/**/*.ext'

Find files matching a given size range:

find root_path -size +500k -size -10M

Run a command for each file (use {} within the command to access the filename):

find root_path -name '*.ext' -exec wc -l {} \;

Find files modified in the last 7 days, and delete them:

find root_path -mtime -7 -delete
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment