- This topic has 1 reply, 1 voice, and was last updated 8 years, 9 months ago by .
Viewing 1 reply thread
Viewing 1 reply thread
- You must be logged in to reply to this topic.
› Forums › Basic skills › Programming › Shell scripting (in bash) › Finding files
A very common task in a shell script is to find all files matching some pattern, then to perform the same operation to all of them. The simple way to do this is with the shell’s built-in filename matching. This is called “globbing” for historical reasons:
$ for F in ~/Desktop/*.txt > do > echo file found: ${F} > done file found: /Users/simonk/Desktop/p.txt file found: /Users/simonk/Desktop/p2.txt file found: /Users/simonk/Desktop/x.txt
which is fine, but may fail when a very long list of files is matched. A smarter way to do this is with the ‘find’ command, which can execute a command on every file matched:
find ~/Desktop -name "*.txt" -depth 1 -exec echo file found: {} \;
which looks pretty complex at first. Note how I’ve placed quotes around “*.txt” to protect it from being immediately expanded by the shell (into any files in the current directory that happen to match). I want that passed to ‘find’ intact as the pattern to look for.
The ‘{}’ will be replaced by each matching filename in turn by ‘find’. The ‘\;’ indicates the end of the command.
It’s well worth getting to grips with ‘find’ because it is very powerful. It can find files or directories. It can recurse into directories (that’s the default, which is why I’ve used ‘-depth 1’ above to prevent that). It can look at timestamps and much more.
How about finding all your LaTeX source files:
find ~/Documents -name "*.tex"
or finding all your large files:
find ~ -size +10M
Maybe you’d like to fix the permissions on all files and directories below the current directory:
find . -type f -exec chmod u+rw,go+r {} \; find . -type d -exec chmod u+rwx,go+rx {} \;
Some forums are only available if you are logged in. Searching will only return results from those forums if you log in.
Copyright © 2024 · Balance Child Theme on Genesis Framework · WordPress · Log in