Linux strings 命令本身并不支持自定義輸出格式。其主要功能是從二進制文件中提取可打印字符串。 要實現自定義輸出,需要結合其他工具或腳本進行處理。
1. 利用文本處理工具:
awk, sed 和 grep 等文本處理工具可以對 strings 命令的輸出進行過濾和格式化。例如,僅顯示包含特定關鍵詞 “keyword” 的字符串:
strings binary_file | grep "keyword"
2. 重定向輸出并編輯:
將 strings 命令的輸出重定向到文件,然后使用文本編輯器或腳本進行手動或自動編輯。
3. 編寫自定義腳本:
編寫腳本(例如 Python 腳本)來處理 strings 命令的輸出,實現更復雜的格式化。以下是一個 Python 示例,將輸出格式化為每行一個字符串:
#!/usr/bin/env python3 import subprocess binary_file = "your_binary_file_here" # 替換為你的二進制文件路徑 try: output = subprocess.check_output(["strings", binary_file], text=True) for line in output.splitlines(): print(line) except FileNotFoundError: print(f"Error: File '{binary_file}' not found.") except subprocess.CalledProcessError as e: print(f"Error executing strings command: {e}")
將代碼保存為 custom_strings.py,賦予執行權限 (chmod +x custom_strings.py) 后運行 ./custom_strings.py。 這個腳本還加入了錯誤處理,更健壯。
通過以上方法,你可以根據需求靈活地控制 strings 命令的輸出格式。