[UNIX] Does the-r option of the grep tool not work?

Source: Internet
Author: User

To search for the keyword char in the. cpp file of the current directory and subdirectory, type:

Grep-r char *. cpp

Failed.

After looking for a long time, I found this fact:

-The R option does enter recursive matching of subdirectories, but the premise is that the subdirectory name must also meet the naming rules of *. cpp. That is to say, the above command is applied to the following directory layers:

./1.cpp

./2.cpp

./Dir. CPP/3.cpp

./DIR/4.cpp

Where./DIR/4. cpp because the directory name does not meet *. cpp naming rules, 4. cpp files will not be involved in matching...

 

The correct solution should be introduced into the pipeline:

Find-type F-name *. cpp | xargs grep char

 

Because my application is not suitable for pipelines, I eventually reduced the requirement and changed to match all files including. cpp:

Grep-r char *

 

In addition, the grep behavior does not conform to the intuition of the Windows programmer. Actually there are two points (different from findstr/s char *. cpp in Windows ):

1. After-R is enabled, only the top-level sub-directory names that meet the rule will go deep into the directory recursion. For commands starting with my article, the contents of the file./CPP/1. cpp will be matched, while the file./DIR/2. cpp will not.

2. After-R is enabled, once the top-level sub-directories meet the rules, the deeper sub-files under the sub-files are no longer restricted by naming rules, and the sub-files are directly involved in content matching. That is,./CPP/1.txt and./CPP/DIR/2.txt are matched.

 

Summary:

Grep-r char *. naming rules in CPP *. CPP is used to constrain top-level sub-directories and sub-files. By filtering the top-level sub-directories, all the deeper sub-files under it are filtered by name.

In Windows, findstr/s char *. CPP, where *. CPP is used to constrain all depth sub-file names, while sub-directories at all levels are unconditionally traversed (I personally think this behavior is more natural ).

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.