~/cheatsheets/find
Published on

Find

Find files based on content

Find all files with a txt extension that includes penguin. -H prints out the filename and -i searches case insensitively.

find . -name "*txt" -exec grep -Hi penguin {} \;

Find files based on Regex

find . -type f -regextype posix-extended -regex '.*[0-9]\s.*'

Find and replace text

In the following example, we replace module.example with module.primary[0].example in .tf files only

Mac OS

  • sed takes the argument after -i as the extension for backups. Provide an empty string (-i '') for no backups.
  • -type f is so it only attempts to work on files
  • {} + means that find will append all results as arguments to one instance of the called command, instead of re-running it for each result.
find . -type f -name '*.tf' -exec sed -i '' 's/module\.example\./module\.primary[0]\.example\./g' {} +

Run command on each directory

Note: \( ! -name . \) avoids executing the command in the current directory.

find . -maxdepth 1 -type d \( ! -name . \) -exec bash -c "cd '{}' && pwd" \;

Move files based on regex

Uses find's -exec option, which replaces {} with each find result in turn, and runs the command you give it

find . -type f -regextype posix-extended -regex '.*[0-9]\s.*' -exec mv -t path_B {} +

On Mac, -regextype isn't supported, so use -E:

find -E . -type f -regex '.*[0-9]\s.*' -exec mv -t path_B {} +

Copy files based on regex

Uses find's -exec option, which replaces {} with each find result in turn, and runs the command you give it

find . -type f -regextype posix-extended -regex '.*[0-9]\s.*' -exec cp "{}" ../patch_B \;

On Mac, -regextype isn't supported, so use -E:

find -E . -type f -regex '.*png' -exec cp "{}" ../logos \;