方法1:使用find和xargs命令
find dir | xargs grep str,dir是指某个目录
find file | xargs grep str,file是指某个文件
注意:这种方法,会递归搜索子目录
方法2:直接使用grep命令
grep str dir/*,dir是指某个目录,但不递归搜索其子目录
grep -r str dir/*,使用-r选项,递归搜索其子目录
grep str file,file是指某个文件
方法3:综合以上两种,写一个shell脚本,代码如下
这样一来,不管$1参数是目录还是文件,都能处理,使用示例如下:
findstr /usr/include main 不递归搜索子目录,大小写敏感
findstr /usr/include main -i 不递归搜索子目录,忽略大小写
findstr /usr/include main -r 递归搜索子目录,大小写敏感
findstr /usr/include main -r -i 递归搜索子目录,忽略大小写
findstr main.cpp main 在文件中搜索,大小写敏感
findstr main.cpp main -i 在文件中搜索,忽略大小写
上面所述的示例中,str不限于特定的文本,可以是带正则表达式的匹配模式。而第3种方法,也可以用sed替换grep来显示文本行,在此基础上能作更多的处理,比如格式化显示、统计匹配的文本个数、搜索策略等,在此就不详究了。![]()
find dir | xargs grep str,dir是指某个目录
find file | xargs grep str,file是指某个文件
注意:这种方法,会递归搜索子目录
方法2:直接使用grep命令
grep str dir/*,dir是指某个目录,但不递归搜索其子目录
grep -r str dir/*,使用-r选项,递归搜索其子目录
grep str file,file是指某个文件
方法3:综合以上两种,写一个shell脚本,代码如下
1
#! /bin/bash
2
# findstr.sh
3![]()
4
if [ $# -lt "2" ]; then
5
echo "Usage: `basename $0` path name [option]"
6
exit 1
7
fi
8![]()
9
path=$1
10
name=$2
11
shift
12
shift
13![]()
14
for option in "$@"
15
do
16
case $option in
17
-r) dir_op="-r"
18
;;
19
-i) lu_op="-i"
20
;;
21
*) if [ -n "$option" ]; then
22
echo "invalid option"
23
exit 1
24
fi
25
;;
26
esac
27
done
28![]()
29
grep_str_of_file()
30
{
31
file=$1
32
str=$2
33
out=$(grep -n $lu_op "$str" "$file")
34
if [ -n "$out" -a "$file" != "$0" ]; then
35
echo "$file: $out"
36
fi
37
}
38![]()
39
find_str()
40
{
41
if [ -d "$1" ]; then
42
for file in $1/*
43
do
44
if [ "$dir_op" = "-r" -a -d "$file" ]; then
45
find_str $file $2
46
elif [ -f "$file" ]; then
47
grep_str_of_file $file $2
48
fi
49
done
50
elif [ -f "$1" ]; then
51
grep_str_of_file $1 $2
52
fi
53
}
54![]()
55
find_str $path $name

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

findstr /usr/include main 不递归搜索子目录,大小写敏感
findstr /usr/include main -i 不递归搜索子目录,忽略大小写
findstr /usr/include main -r 递归搜索子目录,大小写敏感
findstr /usr/include main -r -i 递归搜索子目录,忽略大小写
findstr main.cpp main 在文件中搜索,大小写敏感
findstr main.cpp main -i 在文件中搜索,忽略大小写
上面所述的示例中,str不限于特定的文本,可以是带正则表达式的匹配模式。而第3种方法,也可以用sed替换grep来显示文本行,在此基础上能作更多的处理,比如格式化显示、统计匹配的文本个数、搜索策略等,在此就不详究了。