The 1st method is to use the find and xargs commands. The example is as follows:
Find dir | xargs grep str, dir indicates a directory
Find file | xargs grep str, file refers to a file
Note: This method recursively searches for subdirectories.
The 2nd method is to directly use the grep command. The example is as follows:
Grep str dir/*, dir refers to a directory, but does not Recursively search its subdirectories
Grep-r str dir/*. Use the-r option to Recursively search its subdirectories.
Grep str file, file refers to a file
The 3rd method is to combine the above two methods and write a shell script. The Code is as follows:
#! /Bin/bash
# Find_str.sh
If [$ #-lt "2"]; then
Echo "Usage: 'basename $ 0' path name [option]"
Exit 1
Fi
#! -R indicates recursive processing of subdirectories, and-I indicates case-insensitive.
Path = $1
Name = $2
Shift
Shift
For option in "$ @"
Do
Case $ option in
-R) dir_op = "-r"
;;
-I) lu_op = "-I"
;;
*) If [-n "$ option"]; then
Echo "invalid option"
Exit 1
Fi
;;
Esac
Done
Grep_str_of_file ()
{
File = $1
Str = $2
Out = $ (grep-n $ lu_op "$ str" "$ file ")
If [-n "$ out"-a "$ file "! = "$0"]; then
Echo "$ file: $ out"
Fi
}
Find_str ()
{
If [-d "$1"]; then
For file in $1 /*
Do
If ["$ dir_op" = "-r"-a-d "$ file"]; then
Find_str $ file $2
Elif [-f "$ file"]; then
Grep_str_of_file $ file $2
Fi
Done
Elif [-f "$1"]; then
Grep_str_of_file $1 $2
Fi
}
Find_str $ path $ name
In this way, no matter whether the $1 parameter is a directory or a file, it can be processed as follows:
./Find_str/usr/include main non-recursive search for subdirectories, case sensitive
./Find_str/usr/include main-I do not Recursively search for subdirectories, case-insensitive
./Find_str/usr/include main-r recursive search subdirectory, case sensitive
./Find_str/usr/include main-r-I recursive search subdirectory, case-insensitive
./Find_str main. cpp main search in the file, case sensitive
./Find_str main. cpp main-I search in the file, case-insensitive
In the above example, str is not limited to specific text and can be a matching mode with a regular expression.
In the 3rd methods, you can also use sed to replace grep to display text rows. On this basis, you can perform more processing,
For example, formatting and displaying, counting the number of matched texts, and searching policies are not detailed here.