grep
和 strings
命令可以在 Linux 系統中一起使用,以便在文本文件或二進制文件中搜索特定的字符串
假設你有一個名為 example.txt
的文本文件,你想在其中搜索包含 “example” 的行。你可以使用以下命令:
grep "example" example.txt
如果你有一個名為 example.bin
的二進制文件,你想在其中搜索包含 “example” 的字符串。你可以使用 strings
命令將二進制文件中的可打印字符串提取到一個臨時文本文件中,然后使用 grep
命令搜索該文本文件。例如:
strings example.bin > temp.txt
grep "example" temp.txt
rm temp.txt
如果你想在多個文件中搜索字符串,可以使用 grep
的 -r
(遞歸)選項。例如,如果你想在當前目錄及其子目錄中的所有文本文件中搜索 “example”,可以使用以下命令:
grep -r "example" --include \*.txt
grep
和 strings
命令搜索二進制文件:如果你想在多個二進制文件中搜索字符串,可以將上述方法結合起來。例如,如果你想在當前目錄及其子目錄中的所有二進制文件中搜索 “example”,可以使用以下命令:
for file in $(find . -type f -iname \*.bin); do
strings "$file" | grep -q "example" && echo "Found in $file"
done
這個命令首先使用 find
命令查找所有擴展名為 .bin
的文件,然后對每個文件執行 strings
和 grep
命令。如果找到匹配項,它將輸出包含 “example” 的文件名。