本文目录导读:

Python脚本(跨平台)
#!/usr/bin/env python3
import os
import re
from pathlib import Path
def search_files(directory, keyword, file_extensions=None):
"""按关键词搜索文件内容"""
results = []
directory = Path(directory)
if not directory.exists():
print(f"目录 {directory} 不存在")
return results
for file_path in directory.rglob('*'):
# 检查文件扩展名
if file_extensions and file_path.suffix not in file_extensions:
continue
# 只处理文件,跳过目录
if not file_path.is_file():
continue
try:
# 尝试以文本方式读取
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
# 搜索关键词
if keyword.lower() in content.lower():
# 找到关键词出现的位置(前后显示一些上下文)
lines = content.split('\n')
for i, line in enumerate(lines, 1):
if keyword.lower() in line.lower():
results.append({
'file': str(file_path),
'line': i,
'content': line.strip()
})
except (IOError, OSError):
# 跳过无法读取的文件
continue
return results
# 使用示例
if __name__ == "__main__":
search_dir = "/path/to/search" # 修改为要搜索的目录
keyword = "your_keyword" # 修改为要搜索的关键词
# 可选:只搜索特定类型文件
extensions = ['.txt', '.py', '.md', '.js', '.html']
results = search_files(search_dir, keyword, extensions)
print(f"找到 {len(results)} 个匹配结果:")
for result in results[:20]: # 只显示前20个结果
print(f"{result['file']}:{result['line']} - {result['content'][:100]}")
Linux/Unix Shell脚本
#!/bin/bash
关键词搜索文件
search_directory=$1
keyword=$2
file_pattern=$3
if [ -z "$search_directory" ] || [ -z "$keyword" ]; then
echo "用法: $0 <搜索目录> <关键词> [文件模式]"
echo "示例: $0 /home/user 'important' '*.txt'"
exit 1
fi
if [ -z "$file_pattern" ]; then
# 默认搜索所有文件
find "$search_directory" -type f -exec grep -l -i "$keyword" {} \; 2>/dev/null
else
# 按文件模式搜索
find "$search_directory" -type f -name "$file_pattern" -exec grep -l -i "$keyword" {} \; 2>/dev/null
fi
Windows PowerShell脚本
param(
[string]$SearchPath = ".",
[string]$Keyword,
[string]$FilePattern = "*.*"
)
function Search-Files {
param(
[string]$Path,
[string]$Keyword,
[string]$Pattern
)
if (-not (Test-Path $Path)) {
Write-Error "路径不存在: $Path"
return
}
Get-ChildItem -Path $Path -Recurse -File -Filter $Pattern |
ForEach-Object {
try {
$content = Get-Content -Path $_.FullName -Raw -ErrorAction Stop
if ($content -match $Keyword) {
[PSCustomObject]@{
File = $_.FullName
Size = $_.Length
Modified = $_.LastWriteTime
}
}
}
catch {
# 跳过无法读取的文件
}
}
}
# 使用示例
Search-Files -Path "C:\Documents" -Keyword "report" -Pattern "*.docx"
高级Python脚本(带进度显示和多种选项)
#!/usr/bin/env python3
import os
import argparse
import fnmatch
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
class FileSearcher:
def __init__(self, root_dir, keyword, extensions=None, case_sensitive=False):
self.root_dir = Path(root_dir)
self.keyword = keyword if case_sensitive else keyword.lower()
self.extensions = extensions
self.case_sensitive = case_sensitive
self.results = []
def search_file(self, file_path):
"""在单个文件中搜索关键词"""
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
lines = f.readlines()
matches = []
for line_num, line in enumerate(lines, 1):
content = line if self.case_sensitive else line.lower()
if self.keyword in content:
matches.append({
'file': str(file_path),
'line': line_num,
'content': line.strip()[:200]
})
return matches
except Exception:
return []
def search(self, max_workers=4):
"""并行搜索所有文件"""
files_to_search = []
# 收集所有需要搜索的文件
for file_path in self.root_dir.rglob('*'):
if not file_path.is_file():
continue
# 检查文件扩展名
if self.extensions:
if file_path.suffix not in self.extensions:
continue
files_to_search.append(file_path)
# 使用线程池并行搜索
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = [executor.submit(self.search_file, f) for f in files_to_search]
for future in futures:
result = future.result()
if result:
self.results.extend(result)
return self.results
def main():
parser = argparse.ArgumentParser(description='按内容关键词搜索文件')
parser.add_argument('directory', help='要搜索的目录')
parser.add_argument('keyword', help='搜索关键词')
parser.add_argument('-e', '--extensions', nargs='+',
help='文件扩展名过滤,如 .txt .py')
parser.add_argument('-c', '--case-sensitive', action='store_true',
help='区分大小写')
parser.add_argument('-w', '--max-workers', type=int, default=4,
help='最大并行工作线程数')
parser.add_argument('--limit', type=int, default=50,
help='显示结果数量限制')
args = parser.parse_args()
searcher = FileSearcher(
args.directory,
args.keyword,
args.extensions,
args.case_sensitive
)
print(f"正在搜索关键词 '{args.keyword}'...")
results = searcher.search(args.max_workers)
print(f"\n找到 {len(results)} 个匹配结果:")
for result in results[:args.limit]:
print(f"[{result['file']}:{result['line']}] {result['content']}")
if len(results) > args.limit:
print(f"... 还有 {len(results) - args.limit} 个结果未显示")
if __name__ == "__main__":
main()
使用示例
-
Python脚本:
python file_searcher.py /home/user/documents "重要信息" -e .txt .docx
-
Shell脚本:
chmod +x search.sh ./search.sh /home/user "keyword" "*.txt"
-
PowerShell:
.\search.ps1 -SearchPath "C:\Documents" -Keyword "report" -FilePattern "*.txt"
注意事项
- 性能优化:搜索大文件时可能较慢,建议限制文件类型
- 编码处理:脚本使用UTF-8编码,处理其他编码可能需要调整
- 权限问题:确保有读取目标文件的权限
- 二进制文件:脚本会自动跳过无法以文本打开的文件
这些脚本可以根据您的具体需求进行修改和扩展。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播