Combining Multiple Search Criteria
The find
command becomes even more powerful when you combine multiple search criteria. You can use logical operators to create complex search patterns.
Using AND Logic
By default, when you specify multiple criteria, find
uses AND logic, meaning all conditions must be true. For example, to find all text files larger than 100 bytes:
find ~/project/files -type f -name "*.txt" -size +100c
This command finds files that are both text files AND larger than 100 bytes.
Using OR Logic with -o
To use OR logic, you can use the -o
option. For example, to find files that are either text files OR PDF files:
find ~/project/files -type f \( -name "*.txt" -o -name "*.pdf" \)
Note the use of parentheses, which must be escaped with backslashes. This command finds files that match either condition.
The output should include:
/home/labex/project/files/documents/report.txt
/home/labex/project/files/documents/notes.txt
/home/labex/project/files/documents/important_report.txt
/home/labex/project/files/documents/exact_size.txt
/home/labex/project/files/documents/project.pdf
Using NOT Logic with !
To negate a condition, use the !
operator. For example, to find all files that are not text files:
find ~/project/files -type f ! -name "*.txt"
This command finds all files that do NOT have a .txt extension.
Complex Examples
Let's try some more complex combinations. For example, to find all files that are:
- Either JPG or PNG images AND
- Larger than 0 bytes
find ~/project/files -type f \( -name "*.jpg" -o -name "*.png" \) -size +0c
To find all files in the documents directory that are not PDF files:
find ~/project/files/documents -type f ! -name "*.pdf"
Let's create some additional files to demonstrate a more complex search:
## Create some large and small image files
echo "This is a large JPG file" > ~/project/files/images/large_image.jpg
for i in {1..50}; do
echo "Adding content to make this file larger." >> ~/project/files/images/large_image.jpg
done
touch ~/project/files/images/empty_image.png
Now, let's find all image files (JPG or PNG) that are either empty OR larger than 1KB:
find ~/project/files/images -type f \( -name "*.jpg" -o -name "*.png" \) \( -size 0 -o -size +1k \)
This complex command demonstrates how you can create sophisticated search criteria by combining multiple conditions with logical operators.