A nice CLI question!
You can use the find and rm commands together to delete text files (*.txt) that contain the word "free" in their name. Here are a few ways to do it:
Method 1: Using find command
find . -type f -name '*free*.txt' -delete
Let's break it down:
find: the command to search for files
.: search in the current directory (and subdirectories, recursively)
-type f: only consider files (not directories)
-name '*free*.txt': match files with names that contain "free" anywhere and have the .txt extension. The * is a wildcard for "any characters before/after 'free'".
-delete: action to take when a match is found: delete the file
Method 2: Using find and rm together
find . -type f -name '*free*.txt' -exec rm {} \;
Similar to the previous example, but instead of -delete, we use:
-exec: execute a command for each match
rm {}: remove the file, where {} is a placeholder for the file name
\;: terminator of the -exec command (don't forget the backslash!)
Method 3: Using rm with globbing (bash only)
shopt -s globstar # enable recursive globbing (bash 4+)
rm **/*free*.txt
Here:
shopt -s globstar: enable the globstar option, which allows ** to match directories recursively (bash 4 and later versions)
rm **/*free*.txt: remove files with names containing "free" and ending with .txt, in the current directory and subdirectories. The ** matches any directory (or subdirectory).
Safety first!
Before running any of these commands, I recommend running a "dry-run" version to see what files would be deleted:
find . -type f -name '*free*.txt' -print
This will just print the matching file names, without deleting them. Verify the list is what you expect, and then run the actual deletion command.
Platform notes:
Choose your preferred method, and be careful when deleting files!