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來顯示文本行,在此基礎上能作更多的處理,比如格式化顯示、統計匹配的文本個數、搜索策略等,在此就不詳究了。