Strangely enough I sometimes have a need to find a file which I don't know exactly where is. Even though I am sure I am the only one with this problem I will try to explain how to search for a file on my computer.
To make this a rather short how-to I will only give some pointers about using the find-command.
If I know part of the filename and file-type
Let's pretend I am looking for a odt-file (LibreOffice text), and I believe it has the word invoice in the filename. I believe the file is in my /home/user folder, so from the terminal I will issue this search command:
find /home/user -type f -iname '*invoice*.odt'
This will search for files (-type f) with the case insensitive (-iname) word invoice and end with .odt.
Search for owner, but exclude a folder
Here is a search checking for files owned by root, but is not in the .git folder:
find . -type f -user root ! -ipath '*.git/*'
As we can see we are using '! -ipath' to exclude the case insensitive path of .git in any subfolder we are searching.
Executing actions on found objects
Let's say we have are going to change the owner of all sub-directories in /home/user from user to newowner if the folder is owned by user. The first thing we need to do is become root by sudo-ing so we can use chown, and then we can type in our command:
find /home/user -mindepth 1 -type d -user user -exec chown newuser:newuser {} \;
Here it is worth noting that we do not want to include the /home/user directory, but only subdirectories.
- So we set the parameter "-mindepth 1" to tell find to report only hits below this first depth.
- Then we tell find to find directories (-type d)
- That are owned by user user (-user user)
Then we tell find to execute the chown command on each of the hits it finds.
- Note the curly braces {} which is a macro for the found object.
- And we want to execute this on each of the hits, so we use the \; at the end.
This is barely scraping the possibilities of the find command. Use the man find command to see an extensive list of options that you can use with find. It is possible to search by when a file was last changed, or if it is older than another file. This command is very useful if you know how to use it right.
No comments:
Post a Comment