› Forums › Basic skills › Programming › Shell scripting (in bash) › Finding files
- This topic has 1 reply, 1 voice, and was last updated 9 years, 12 months ago by
Simon King.
-
AuthorPosts
-
-
January 24, 2016 at 16:37 #2316
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.txtwhich 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
-
March 12, 2016 at 22:28 #2775
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 {} \;
-
-
AuthorPosts
- You must be logged in to reply to this topic.
This is the new version. Still under construction.