目的
使用grep命令,搜索一个目录(包含子目录)下面的多行字符串。查找哪个文件包含该字符串。
例如查找edk2下面的protocol的实现代码。找到了protocol,但是不清楚具体的实现在哪个文件中。可以通过搜索protocol的参数,来找到实现。
grep命令多行匹配的一些小知识
\s+ 表示匹配一个或多个空白字符(包括空格和制表符)。\n 表示匹配换行符。^ 表示以此为行首。
使用python3来快速转换字符串便于grep命令使用
首先将要查找的字符串保存到一个空白文本中。
再写一个脚本,实现以下功能:
1.传入参数为文件名
2. 将给定文件内的字符串,一个或多个连续的空格或制表符用"\s+“代替,换行符用”\n代替",特殊字符添加转义字符"\"
3. 在生成的字符前后添加grep命令与搜索的文件路径
import re
import sys
def preprocess_file(filename):
with open(filename, 'r') as file:
content = file.read()
# 使用正则表达式替换连续的空格或制表符为\s+,换行符为\n,并添加转义字符
processed_content = re.sub(r'([^a-zA-Z0-9\s])', r'\\\1', content)
processed_content = re.sub(r'(\s+)', r'\\s+', processed_content)
processed_content = processed_content.replace('\n', '\\n')
# 在处理后的内容前后添加字符串
processed_content = ' grep -r -zE "(' + processed_content + ')" ./'
# 将处理后的内容写入新文件
new_filename = filename + "_cmd.sh"
with open(new_filename, 'w') as new_file:
new_file.write(processed_content)
print("处理完成!新文件保存为:", new_filename)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("使用说明:")
print("python preprocess_script.py <filename>")
print("<filename>: 要处理的文件名")
sys.exit(1)
filename = sys.argv[1]
preprocess_file(filename)
运行脚本:
python3 grep.py test.txt
生成包含命令内容的文件:
test.txt_cmd.sh
生成的新文件内有完整grep命令,可以直接使用
chmod +x test.txt_cmd.sh
./test.txt_cmd.sh
用这种方式的话,会打印整个包含所需字符串的文件内容出来。可以将结果保存到一个文本中,再在结果中查找。
./test.txt_cmd.sh > test.txt
搜索关键字"@file"可以找到包含对应字符串的文件。
另一种grep用法
alias grepx='test() { grep -Pzor "($1)(\r\n|\()$2" $3;};test'
alias grepux='test() { grep -Pzor "(EFIAPI|VOID|ASM_FUNC|RETURN_STATUS|EFI_STATUS)(\r\n|\()$1" $2;};test'