To find all files which contain a certain string, you can use just grep on its own:
grep -R /path/to/directory "myword"
In the example above, "myword"
is what you're looking for, and /path/to/directory
is the directory you want to search through. -R
tells grep
to run a recursive search (i.e. to start at the path you specified, and go into each subdirectory in there).
EDIT
I've re-read your question and I think you're looking for how to find files that have a certain filename. For this use:
find /path/to/directory -name "*glob*" -print
where /path/to/directory
is where you want to start your search (and find
will also look in the subdirectories) and "*glob*"
is a full or a partial file name that you want to look for. Please note, you can use wildcards (.
and *
for any single and any multiple characters match, respectively) in the glob. As a variation to this, you can use, as proposed by others:
find /path/to/directory -name "*glob*" -exec ls -la {} \;
in the above, what you put after the option -exec
is any UNIX command with paramteres (in this case ls -la
). The {}
will be substituted by the file name find
finds, and the \;
is a termination string.
EDIT 2
Please note, the commands above give you similar results to Spotlight, but they don't use Spotlight at all.
If you'd like to use Spotlight from command line, you can use mdfind
command, which is a command-line interface for Spotlight. Typing mdfind
on its own will give you a quick help for using it with a few examples. man mdfind
will give you a more detailed manual for it.
Essentially mdfind
takes a search string (and optional modifiers) as it's argument and it's the same as you would type in Spotlight's text field when using it in a GUI.
Untested
find . -depth -print0 |
while IFS= read -d '' -r file; do
dir=$(dirname "$file")
base=$(basename "$file")
base=${base//[[:space:]]/_} # change whitespace to underscores
base=${base//[^[:alnum:]_.]/} # delete any chars not alphanumeric _ .
newname="$dir/$base"
if [[ -e $newname ]]; then
echo "'$newname' exists, not renaming '$file'"
else
echo mv "$file" "$newname"
fi
done
If it looks OK, remove the "echo"
The key here is the "-depth" option to find. It will emit "./sub dir/file name" before "./sub dir". Otherwise if "./sub dir" is renamed to "./subdir", then you'll get a 'file not found' error when the while loops gets to "./sub dir/file name". Also, it means you don't need different logic for directories.
The "-print0" option to find and the busy-ness around the read command are to ensure filenames with spaces are handled properly.
Best Answer
There are several things in your script which can make it go wrong: