A find command tip
I use the find command a lot to look for files, whether in bash scripts or straight from the command line.
An interesting trick is excluding some files from the list. For example, I recently needed to look for all “.md” files but wanted to exclude everything starting with an underscore, as well as the “default.md” file.
To do that I used the -not parameter before the -name parameter, as in the example below.
find . \
-type f \
-name '*.md' \
-not -name '_*md' \
-not -name 'default.md'
Deleting files
In my case I wanted to delete the files while keeping the rest of the structure intact, so I used the command line below, with the only change being replacing echo with rm. I left the echo command in the example to keep it safer for anyone who just wants to copy the command and test it out.
find . \
-type f \
-name '*.md' \
-not -name '_*md' \
-not -name 'default.md' \
-exec echo {} \;
In this example, the -type f parameter tells find that we only want files, not directories. Next, the -name ‘*.md’ parameter asks it to search for all .md files. The two -not -name commands exclude the files we don’t want.
Finally, the -exec echo {} ; parameter runs the echo command and replaces the curly braces {} with the name of the file found.