Advanced technology for using the Unix find command

Source: Internet
Author: User
Tags tmp file

UNIX operating systems are like vast, unlabeled wilderness. When traveling in such a field, you can select some tools that will help you in the future.findCommand is such a tool.findCommands can be used not only to locate files, but also to automatically execute sequences of other UNIX commands as described in this article, where the file names found are used as input.

Find restrictions

All competent operating systems have tools to help you find relevant content. Unlike most toolsfindThe command automatically performs many operations on the files it finds.

Standard in GuifindTools allow you to perform some common operation tasks on the files found: You can mark them as cut, copy, and paste, you can move them to a new location, you can use the application that creates them to open them. These operations involve two or more steps that are not automatically completed, that is, first find the file and then use the GUI to mark the next operation. This method is fine for many users, but not only does explorer need this method.

UNIXfindCommand to delete, copy, move, and execute the files it finds. In addition-execParameters can automatically run these files according to the sequence of Unix commands you need. It can even be further confirmed before you perform these operations on any file.

Simplify File System Management

Like most Unix commands, UnixfindCommands have a long string of daunting options and switches that prevent people from learning the command in depth, but it is precisely because of its wide range that real explorer will not be intimidated by them. A good general principle will go through a long process to simplify a complicated problem. Start an xterm and execute the following command:

$ find . -name *.gif -exec ls {} /;

-execParameters contain truly valuable operations. When you find a file that matches the search criteria,-execThe parameter defines what operations will be performed on these files. This example tells the computer to perform the following operations:

  1. Search down from the current folder, followedfindThen, use the dot (.).
  2. Locate all files whose names end with. GIF (Graphic files ).
  3. List all the files found. UselsCommand.

 

Need-execParameters. When you find a file name that matches the search criteria,findCommand Executionls {}String, replace the text with the file name and Path{}. Assume that the saturn.gif file is found in the search,findRun the following command:

$ ls ./gif_files/space/solar_system/saturn.gif

The rest of this article is based on this general principle: Use it carefullyfindCommands make the management of UNIX file systems easier. For example, if you use-fstypeParameter,findThe command can process the command according to the type of the file system in which the file is located. InfindThe command will prompt you before executing the corresponding command on the searched file, which is usually very useful, you can use-okThe parameter tells it to continue this operation. Next we will introduce it.

Optional execution

-okYes-execAn important alternative to a parameter, its behavior and-execBut it will prompt whether you want to run the corresponding command on the file. Assume that you want to delete most of the. txt files in the home directory, but you want to perform this operation one by one. For examplermThe delete operation like the command is very dangerous, because when usingfindWhen you use this automated processing method to find files, it may accidentally delete important files. You may want to carefully check these files before deleting them.

The following command lists all. txt files in your home directory. To delete these files, you mustfindWhen you are prompted to confirm the operation by listing the file names, enterYOry:

$ find $HOME/. -name *.txt -ok rm {} /;

It lists every file found, and the system will pause waiting for your inputYOry. If you pressEnterThe system will not delete the file. Listing 1 shows some sample results:

Listing 1. Sample Results

< rm ... /home/bill/./.kde/share/apps/karm/karmdata.txt > ?< rm ... /home/bill/./archives/LDDS.txt > ?< rm ... /home/bill/./www/txt/textfile1.txt > ?< rm ... /home/bill/./www/txt/faq.txt > ?< rm ... /home/bill/./www/programs/MIKE.txt > ?< rm ... /home/bill/./www/programs/EESTRING.txt > ?...

The system will pause after each question mark. In this example, the Enter key is pressed each time to continue processing the next file. (No files are deleted .)-okThe parameter allows you to control the automatic processing of each searched file, so that you can add a security measure to prevent automatic deletion of the file.

If you are using-okWhen too many files are involved in parameters, a good way is to run-execOffindCommand to list all the files to be deleted. After checking that important files are not deleted, run the command again.rmReplacels.

-execAnd-okAre very useful, you must determine which one can work better in the current situation. Remember, security first!

Creative use of find

You can usefindCommand to execute a variety of tasks. This section providesfindCommand to manage the file system.

For simplicity, these examples avoid using-execCommand. However, you can run the find command-execClause.

Clear temporary files

You can usefindCommand to clear temporary files generated during normal use in directories or subdirectories, which can save disk space. To perform this operation, run the following command:

$ find . /( -name a.out -o -name '*.o' -o -name 'core' /) -exec rm {} /;

In bracketsFile maskIdentifies the file type to be deleted.-name. This list can be expanded to include any temporary file types in the system you want to clear. During code compilation and connection, programmers and their tools generate the file types in the example:a.out,*.oAndcore. Other users usually generate similar temporary files, such*.tmp,*.junkTo edit the command. You may also find thatcleanThe script is very useful. You can execute this script when you need to clear the content in a directory.

Copy contents in the directory

findThe command allows you to copy all contents in the directory while maintaining the permissions, time, and ownership of each file and sub-directory. To complete this operation, you need to use it in combinationfindAndcpioCommand:

Listing 2. Using the find and cpio commands in combination

$ cd /path/to/source/dir$ find . | cpio -pdumv /path/to/destination/dir

cpioA command is a replication command designed to copy or copy a cpio or tar archive file, and automatically retain the permissions, time, and ownership of the file and sub-directories.

List the first line of a text file

Some people use the first line of each text file as the title or description of the file content. You can use reports that list file names and the content of all text files in the first line to filter a large number of text files. The following command lists the first line of all text files in your home directory in the report for further use as neededlessCommand to check:

Listing 3. Less command

$ find $HOME/. -name *.txt -exec head -n 1 -v {} /; > report.txt$ less < report.txt

Maintain the storage space of log and TMP files

To maintain the log and tmp file storage space for applications that generate a large number of files, you can run the following commands oncronTask:

Listing 4. Maintaining log and tmp file buckets

$ find $LOGDIR -type d -mtime +0 -exec compress -r {} /;$ find $LOGDIR -type d -mtime +5 -exec rm -f {} /;

The First Command finds all the logs in the $ logdir directory that are contained within 24 hours (-mtime +0Directory of the modified data (-type dAnd compress them (compress -r {}) To save disk space. If these directories exceed one working week (-mtime +5), The second command will delete it (rm -f {}) To increase the available space on the disk. In this way, the cron task automatically maintains the directory according to the specified time window.

Copy a complex directory tree

If you want to copy a complex directory tree from one computer to another, at the same time, the copy permission and the user ID and group ID (UID and GID -- the value of the ownership of the Tag file used by the operating system) are maintained, and the user file is not copied, so you need to use it again.findAndcpio:

Listing 5. copying a complex directory tree

$ cd /source/directory$ find . -depth -print | cpio -o -O /target/directory

Search for links that do not point to any location

You can usefindOfperlInterpreter:

$ find / -type l -print | perl -nle '-e || print';

This command starts from the top-level directory (/) and listsperlThe interpreter is sure not to point to any location (-nle '-e || print'All links (-type l -printFor more information about this technique on the Unix guru universe site, see references. If you want to delete these files, you can use the pipeline to pass the outputrm -f {}Command. Of course, Perl can be found in most UNIX toolkit, one of many powerful explanatory language tools.

 

Locate and rename directories that cannot be printed

In UNIX, malicious programs may create directories containing unprintable characters. Locate and rename these directories to make it easier to check and delete them. To complete this operation, you must firstlsContains-iTo obtain the value of the index node of the directory. Then, usefindConverts the value of an index node to a value that can be used.mvCommand to rename the file name:

Listing 6. Locate and rename directories that cannot be printed

$ ls -ail$ find . -inum 211028 -exec mv {} newname.dir /;

List zero-length files

To list all files with zero length, run the following command:

$ find . -empty -exec ls {} /;

After an empty file is found, you can usermCommand to replacelsCommand to delete these files.

ObviouslyfindThe use of commands is limited by knowledge and creativity.

 

Conclusion

UsefindCommand to easily browse the rich content in the UNIX file system. It is worth the time to experiment with this command and understand what it can do for you. As shown in the example in this article, you can use it in many creative ways.findIn this way, you can easily browse and manage file systems.

References

Learning

  • For more information, see the original article on the developerworks global site.
  • In commands reference, Volume 2, find command, you can learn aboutfindCommand, especially for the ibm aix environment.
  • The UNIX guru universe (UGU) site provides excellent resources for Unix.
  • About how to accelerate by using many available optionsfindFor more information about command search, see uhacc -- presentations: Using find.
  • Linux.com | CLI magic: GNU find describes the usagefindCommand. Note: CLI represents the command line interface, which is opposite to the GUI!
  • The authors of use free software within commercial Unix (developerworks, February 2006) pointed out how to use Unix commands with different functions between different commercial versions, suchfindOrtar. Read about how to install the GNU tool on your commercial UNIX version for compatibility.
  • Follow up on the latest developerworks technical events and network broadcasts.

Discussion

  • Join the developerworks blog to join the developerworks community.

About the author

Bill zimmerly is a knowledge engineer and underlying system programmer with expertise in UNIX and Microsoft Windows of different versions. He is also a free thinker who advocates logical changes. Bill is also considered an irrational person. The reason for this reason is:"Rational people adapt themselves to the world. Irrational people try to adapt the world to themselves. Therefore, all progress depends on irrational people."(George Bernard Shaw ). His hobby is to create new technologies and write related articles. He lives in the outskirts of Hillsboro in Missouri, where the air is fresh and the scenery is pleasant, and there are excellent wine brewing plants everywhere. There is nothing better than writing a Unix shell script while drinking stone Hill blush in a crystal-transparent cup.

 

 

 

Note:

Text Reprinted from: http://www.ibm.com/developerworks/cn/aix/library/es-unix-find.html

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.