aboutsummaryrefslogtreecommitdiffstats
path: root/mypath/search.sh
diff options
context:
space:
mode:
Diffstat (limited to 'mypath/search.sh')
-rwxr-xr-xmypath/search.sh52
1 files changed, 52 insertions, 0 deletions
diff --git a/mypath/search.sh b/mypath/search.sh
new file mode 100755
index 0000000..f55f748
--- /dev/null
+++ b/mypath/search.sh
@@ -0,0 +1,52 @@
1#!/bin/bash
2
3##########################################################################
4# File Name : search.sh
5# Encoding : utf-8
6# Author : We-unite
7# Email : weunite1848@gmail.com
8# Created Time : 2024-03-26 01:15:43
9##########################################################################
10
11set -e
12
13# 在当前文件夹下查找含有指定内容的文件,并输出其文件名、行号和上下文
14# 每个文件先输出文件名,然后输出包含指定内容的行号和上下文
15# 用法:./search.sh <search_content> <context_lines>
16# 允许按顺序缺省参数
17
18# 检查参数个数
19if [ $# -lt 1 ]; then
20 echo "Usage: $0 <search_content> <path> <file_type>"
21 exit 1
22fi
23
24# 检查参数是否为空
25if [ -z "$1" ]; then
26 echo "Error: search_content is empty"
27 exit 1
28fi
29
30if [ -z "$2" ]; then
31 context_lines=3
32else
33 if [ -z "$(echo $2 | grep -E '^[0-9]+$')" ]; then
34 echo "Error: context_lines $2 is invalid"
35 exit 1
36 fi
37 context_lines=$2
38fi
39
40# 查找文件
41find . -type f | while read file; do
42 # 查找文件中包含指定内容的行,存储到变量中
43 lines=$(grep -C "$context_lines" -n "$1" $file | sed 's/:/ /')
44 if [ "$lines" == "" ]; then
45 continue
46 else
47 # 彩色输出文件名
48 echo -e "\033[1;32m$file\033[0m"
49 # 输出包含指定内容的行号和上下文
50 echo -e "$lines"
51 fi
52done