[Linux] Searches for files containing specified content and returns file names

Source: Internet
Author: User

In a Linux system, find and grep are powerful commands that can do many things, and today it's just someone who asks "How to find which files contain specific strings and display the names of those files".

The first method: use grep, assuming that all the. cpp files contain an ' open ' string, and if so, display the file with the following command:

Grep-rl ' open '. --include=*.cpp

The execution results are as follows:

./test/testall/file.cpp
./test/testall/shell_test.cpp
./test/daemontest/main.cpp

But sometimes you just show the file name, and you don't know what the place is, and if you have a way to look at that line, you can use the following command:

Grep-rn ' open '. --include=*.cpp

The results of the execution are as follows:

./test/testall/file.cpp:270:file *file = fopen (File_name.c_str (), "w");
./test/testall/file.cpp:273:printf ("Can ' t Open the file\n");
./test/testall/shell_test.cpp:29:file *file = fopen (file_name, "R");
./test/daemontest/main.cpp:53:openlog ("Daemontest", Log_pid,log_user);

Displays the file name, line number, and the line contents.

Second method: Use the Find command +grep

Suppose the search for all. cpp files contains an ' open ' string, and if it is included, the file is displayed with the following command:

Find-name ' *.cpp '-exec grep-l ' open ' {} \;

The result is as follows:

./test/testall/file.cpp
./test/testall/shell_test.cpp
./test/daemontest/main.cpp




[Linux] Searches for files containing specified content and returns file names

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.