2

10 Example of find command in UNIX and Linux

 3 weeks ago
source link: https://javarevisited.blogspot.com/2018/08/10-example-of-find-command-in-unix-linux.html#axzz8Y54xDxKb
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

10 Example of find command in UNIX and Linux

The find command is one of the most versatile commands in UNIX and Linux, and I used it a lot in my day-to-day work. I believe having a good knowledge of find command in UNIX and understanding of its different options and usage will increase your productivity a lot in UNIX based operating systems, e.g. Redhat Linux or Solaris. If you are a QA, support personnel, and your works involve lots of searching text on Linux machine or if you are a Java or C++ programmer and your code resides in UNIX, find command can significantly help you to look for any word inside your source file in the absence of an IDE.
Loaded: 0.17%
It is the alternative way of searching for things in UNIX; grepis another Linux command which provides similar functionality like find but in my opinion, later is much more potent than grep in UNIX.

Like any other command strength to find lies in its various options, which is worth learning, but, to be frank, hard to remember. If you can be even able to remember all the options mentioned in this article, you will be taking much more advantage of the find command than average developers, QA, support people, and Linux users. 

By the way, I have been sharing my experience on Unix and Linux command, and their different options, usage, and example, and this article are in continuation of my earlier post like how to convert an IP address to the hostname in Linux. If you are new here, you may find these tips useful for your day-to-day development and support work.
By the way, if you are new to Linux then I also suggest you go through a comprehensive Linux course to learn some basic commands and fundamentals like Linux file system, permissions, and other basic things. 
If you need an online course, I highly recommend Linux Mastery: Master the Linux Command Line in 11.5 Hours course on Udemy. It's a very practical and hands-on course to learn Linux fundamentals in a quick time. It's also very affordable and you can buy in just $10 on Udemy flash sales which happen every now and then. 

10 find command examples in Linux and  UNIX

Here I am listing down some of the ways I use to find in Unix or Linux box regularly; I hope this would help someone who is new in UNIX find command or any developer who has started working on the UNIX environment. This list is by no means complete and just some of my favorites, if you have something to share, please share via comments.

1. How to run the last executed find command in UNIX

!findwill repeat the last find command executed. It saves a lot of time if you re searching for something, and you need to run the same command again and again.

javin@testenv1 ~/java : !find
find . -name "*.java"     --last find command executed
./OnlineStockTrading.java
./StockTrading.java
In fact, "!" can be used with any command to invoke the previous run of that command; it's one of the special shell characters. 
If you are not familiar with built-in bash commands and special characters, then I strongly suggest you check outBash Shell Scripting: Crash Course For Beginners. A short course that provides enough information to make the most out of bash shell.  
10 Example of find command in UNIX and Linux

2. How to find files that have been modified less than one day, minute, or hour in Linux

find -mtime is used to search files based upon modification time. This is, in fact, my favorite find command tips while looking out some production issues just to check which files have been modified recently, could be likely cause of the issue, believe me, it helps a lot and many times gives you enough hint of any problem due to intended or unintended file change. 

Along with –mtime, there are two more options related to time, find -atime, which denotes the last accessed time of the file, and find –ctime denotes the last changed time. 

The + sign is used to search for greater than, - sign is used to search for less than and without a sign is used for exact. For example, find –mtime -1 will search all files which have been modified.
javin@testenv1 ~/java : find . -mtime 1  (find all the files modified exact 1 day)

javin@testenv1 ~/java : find . -mtime -1 (find all the files modified less than 1 day)
.
./StockTrading.java

javin@testenv1 ~/java : find . -mtime +1 (find all the files modified more than 1 day)
./.vimrc
./OnlineStockTrading.java
./StockTrading.java~
In this example, since we have only modified StockTrading.java some time back, it has shown on find –mtime -1, rest of the files are not touched today, so they appear as modified more than 1 day while there is no file that has been modified precisely one day.

3. How to find all the files and directories which hold the 777 permission in UNIX

find –perm option is used to find files based upon permissions. You can use find –perm 444 to get all files that allow read permission to the owner, group, and others. 

If you are not sure how those 777 and 444 numbers come up, see my post on file and directory permission in Unix and some chmod examples to change permissions in Unix.

javin@testenv1:~/java $ find . -perm 644
./.vimrc
./OnlineStockTrading.java
I use this find command example to find out all the executable files; you can also modify it to find all the read-only files or files having written permission, etc. 
How? Well, by changing permissions, e.g. to find all read-only files in the current directory: find . –perm 555Here "." or period denotes the current directory. You can replace it with any directory you want.

Btw, if you are not familiar with file permissions, then you should first check outLearn Linux in 5 Days and Level Up Your Career, another excellent course for anyone who wants to work in Linux.
best course to learn Linux for Beginners

4. Case insensitive search using the find in UNIX

How to do case insensitive search using the find command in Unix? Use option “-i" with name, by default, find searches are case sensitive. 

This option of the find is beneficial while looking for errors and exceptions in the log file.
find . –iname "error" –print ( -i is for ignore )
On a different note, find and grep command is also a favorite topic during UNIX Interviews, and interviews often asked questions during interviews on both system admin and application developer jobs.

UNIX find and xargs command Example

Now we will see some UNIX find command examples combined with the xargs command. A combination of find and xargs can be used to do whatever with each file found by find command, for example, we can delete that file, list the content of that file, or can apply any comment on that file.

5. How to delete temporary files using the find command in UNIX

In order to delete files, you can use either –delete option of find command or use xargs in combination. It's better to create a housekeeping script for such tasks which can perform cleanup on a periodic basis.
Find. -name "*.tmp" -print | xargs rm –f
The use of xargs, along with find gives you immense power to do whatever you want with each search result. 

See another example below, also worth considering use of -print0 to avoid problems with whitespace in the path when piping to xargs (use with the xargs -0 option) as suggested by Ebon Elaza.

6. How to find all text file that contains word Exception

find . –name "*.java" –print | xargs grep “MemoryCache”, this will search all java files starting from the current directory for the word "MemoryCache". We can also leave -print option in all cases because it the default for UNIX finds command as pointed out by Ben in the comments.
You can further sort the result of the find command using the Sort command in Unix.
find . –name "*.txt" –print | xargs grep "Exception"

7. Finding files only in the current directory not searching on subdirectories

While using the find command, I realized that sometimes I only need to find files and directories that are new, only in the current directory, so I modified the find command as follows. 

You can use the find –type option to specify the search for the only file, link, or directory, and -maxdepth option specifies how deep the find command has to search.
find . -maxdepth 1 -type f -newer first_file
Another way of doing it is below:
find . -type f -cmin 15 -prune
Means type file, last modified 15 minutes ago, only look at the current directory. (No sub-directories). 
Btw, if you are new to UNIX and don't know what does the dot (.) and double dot (..) mean current directory and parent directory, then first check Linux Command Line Interface (CLI) Fundamentals course on Pluralsight.
10 find command tips in Linux

Example 8 – How to find files based on the size in Unix and Linux

The following find example shows how you can use find –size options to find files based upon a certain size. This willfind all files in the current directory and sub-directory, greater than some size using the find command in UNIX:
find . -size +1000c -exec ls -l {} \;
Always use a c after the number, and specify the size in bytes; otherwise, you will get confused because of find -size list files based on the size of the disk block. 

Also, to find files using a range of file sizes, the minus or plus sign can be specified before the number. The minus sign means "less than," and the plus sign means "greater than." 

Suppose if you want to find all the files within a range, you can use find command as in the below example of find:
find . -size +10000c -size -50000c -print
This find example lists all files that are greater than 10,000 bytes, but less than 50,000 bytes:

Example 9 – How to find files some days older and above a specific size

We can combine –mtime and –size to find files that are some days old and greater than some size in Unix. A prevalent scenario where you want to delete some large old files to free some space in your machine. 

This example of the find command will find which are more than 10 days old and size greater than 50K.
find . -mtime +10 -size +50000c -exec ls -l {} \;

10. Find and AWK

You can use "awk" in a combination of find to print a formatted output, e.g. next command will find all of the symbolic links in your home directory, and print the files your symbolic links points to:
find . -type l -print | xargs ls -ld | awk '{print $10}'
The "." says starts from the current directory and include all subdirectory and  "-type l" says list all links.
Hope you find this useful, please share how you are using find commands, and we can benefit from each other's experience and work more efficiently in UNIX.


Tip: 
$* :    $* is one of the special bash parameters which is used to expand positional parameters from position one. if you give double quotes and expansion is done within double quotes, it only expands to a single word, and the corresponding value of each parameter will be separated by the first letter of the IFS environment variable defined in bash. 

How to use find command on filenames with space in UNIX

I have received a lot of comments from my readers on not mentioning find -print0 and xargs -0 on find examples, so I thought to include this as well. When we don't specify any expression after the find command, the default option is -print, which prints the name of each found file followed by \n or newline

Since we mostly pipe the output of the find command to xargs -print could cause a problem if the file name itself contains a new line or any form of white space. To resolve this issue instead of -print use -print0

The difference between find -print and find -print0 is print0 display file name on the stdout followed by a "NUL" character, and then you can use xargs -0 commands to process file names with a null character. 

let's see UNIX find command example with a file name having space in them:
javin@testenv1:~/test find . -name "*equity*" -print
./cash equity trading ./equity~
You see here "cash equity trading" has space in there name
javin@testenv1:~/test find . -name "*equity*" -print | xargs ls -l
ls: cannot access ./cash: No such file or directory
ls: cannot access equity: No such file or directory
ls: cannot access trading: No such file or directory
-r--r--r-- 1 stock_trading cash_domain trading 0 Jul 15 11:42 ./equity~
Now, if we pass this to xargs, xargs treat them as three separate files.
javin@testenv1:~/test find . -name "*equity*" -print0 | xargs ls

xargs: WARNING: a NUL character occurred in the input.  It cannot be passed through in the argument list.  Did you mean to use the --null option?

ls: cannot access ./cash: No such file or directory
ls: cannot access equity: No such file or directory
ls: cannot access trading: No such file or directory
Now to solve this, we have used the find command with -print0, which appends NUL character on the file name, but without xargs -0, the xargs command would not be able to handle those inputs.
javin@testenv1:~/test find . -name "*equity*" -print0 | xargs -0 ls -l
-rw-r--r-- 1 stock_trading cash_domain trading 0 Jul 21 09:54 ./cash equity trading
-r--r--r-- 1 stock_trading cash_domain trading 0 Jul 15 11:42 ./equity~
Now you can see with find -print0| xargs -0 it looks good

In short, always use find -print0 along with xargs -0 if you see the slightest possibility of file names containing space in UNIX or Linux. 
These are some of the most common and useful examples of find command in Linux and if you are interested in more and If you love to read books,  you can also take a look at The Linux Command Line: A Complete Introduction, a great book, and must-read for any programmer, tester, system administrator, security guy or developers, who work on UNIX and Linux based environment. 
10 ways to use find command in UNIX and Linux
It not only teaches about find and grep but also introduces several useful commands, which have probably have gone unnoticed by many of us. And, if you like online courses, here is a list of 5 free Linux courses to start your journey into the beautiful world o the Linux command line. 

Essential points about find commands in UNIX and Linux

Here are some of the important and interesting things to know about powerful find command, most of these points are contributed by various people in comments, and big thanks to all of them for sharing their knowledge, you should definitely check out comments to know more about find command:
1.  find –print and find is the same as –print is a default option of the find command.
2. find –print0 should be used to avoid any issue with white space in file name or path while forwarding output to xargs, also use xargs -0 along with find –print0.
3. find has an option called –delete which can be used in place of  -exec rm {} \;
Related post:
Thanks a lot for reading this article so far. If you find these Linux find command examples useful, then please share them with your friends and colleagues. If you have any other interesting find examples to share, then please drop a note.

P. S. - If you want to learn Linux from scratch and looking for some free resources, then you can also check out this list of free Linux courses for Programmers and Developers. It contains some of the free online courses from Udemy, Pluralsight, and Coursera to learn Linux online. 

Recommend

  • 39

    Error 1020 Ray ID: 5ae361e98d180538 • 2020-07-05 19:09:48 UTC Access denied What happened? This website is using a security service to protect itself from online attacks...

  • 6

    15 Practical Grep Command Examples In Linux / UNIX by SathiyaMoorthy on March 26, 2009

  • 8
    • www.thegeekstuff.com 3 years ago
    • Cache

    Unix LS Command: 15 Practical Examples

    ls – Unix users and sysadmins cannot live without this two letter command....

  • 10
    • www.thegeekstuff.com 3 years ago
    • Cache

    UNIX / Linux: 10 Netstat Command Examples

    Netstat command displays various network related information such as network connections, routing tables, interface statistics, masquerade connections, multicast memberships etc., In this article, let us review 10 practical unix

  • 0
    • massimo-nazaria.github.io 3 years ago
    • Cache

    Unix Philosophy with an Example

    Unix Philosophy with an Example Mar 2, 2019 The Unix philosophy is a set of software development concepts and norms which have shaped th...

  • 3
    • commandcenter.blogspot.com 2 years ago
    • Cache

    command center: Unix Quiz

    Unix Quiz (Here's another resurrected post from April 30, 2012. Answers in a followup.) People objected that there was no Exit item on the main menu for the mpx program that put windows on the Blit; see 

  • 6
    • commandcenter.blogspot.com 2 years ago
    • Cache

    command center: Unix Quiz answers

    Unix Quiz answers (Here's the next resurrected post, this time from Jun 8, April 30, 2012.) A while back I posted the questions from the 1984 Unix/mpx Exit quiz: 

  • 2
    • siongui.github.io 2 years ago
    • Cache

    [Golang] Parse Unix Time (utime) Example

    Introduction When I tried to get the timestamp of the Facebook post, I found that the timestamp...

  • 4

    This blog post documents my understanding of how the conventions for Unix command line syntax have evolved over time. It’s not properly sourced, and may well be quite wrong. I’ve not been using Unix until 1989, so I wasn’t there for the early year...

  • 10

    Bash-Oneliner and GameShell Teach Unix Command Line

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK