本文目录导读:

Windows PowerShell 脚本
# find-file.ps1
param(
[Parameter(Mandatory=$true)]
[string]$FileName,
[string]$SearchPath = "C:\",
[switch]$Recurse = $true
)
Write-Host "搜索文件: $FileName" -ForegroundColor Green
Write-Host "搜索路径: $SearchPath" -ForegroundColor Green
$results = Get-ChildItem -Path $SearchPath -Filter "*$FileName*" -Recurse:$Recurse -ErrorAction SilentlyContinue
if ($results.Count -gt 0) {
Write-Host "找到 $($results.Count) 个文件:" -ForegroundColor Cyan
$results | Select-Object FullName, Length, LastWriteTime | Format-Table -AutoSize
} else {
Write-Host "未找到匹配的文件。" -ForegroundColor Yellow
}
使用方式:
.\find-file.ps1 -FileName "report" -SearchPath "D:\Documents"
Linux/macOS Shell 脚本(bash)
#!/bin/bash
# find-file.sh
usage() {
echo "用法: $0 -n <文件名> [-p <搜索路径>]"
echo " -n 文件名(支持通配符)"
echo " -p 搜索路径(默认当前目录)"
exit 1
}
# 默认值
SEARCH_PATH="."
FILE_NAME=""
# 解析参数
while getopts "n:p:" opt; do
case $opt in
n) FILE_NAME="$OPTARG" ;;
p) SEARCH_PATH="$OPTARG" ;;
*) usage ;;
esac
done
# 检查文件名参数
if [ -z "$FILE_NAME" ]; then
echo "错误: 必须指定文件名"
usage
fi
echo "搜索文件: $FILE_NAME"
echo "搜索路径: $SEARCH_PATH"
# 使用 find 命令搜索
find "$SEARCH_PATH" -type f -name "*${FILE_NAME}*" 2>/dev/null | while read -r file; do
# 获取文件信息
size=$(stat -c%s "$file" 2>/dev/null || stat -f%z "$file" 2>/dev/null)
modified=$(stat -c%y "$file" 2>/dev/null || stat -f%Sm "$file" 2>/dev/null)
echo "找到: $file (大小: $size 字节, 修改时间: $modified)"
done
# 显示计数
count=$(find "$SEARCH_PATH" -type f -name "*${FILE_NAME}*" 2>/dev/null | wc -l)
echo "共找到 $count 个文件"
使用方式:
chmod +x find-file.sh ./find-file.sh -n "report" -p "/home/user/documents"
Python 跨平台脚本(推荐)
#!/usr/bin/env python3
# find_file.py
import os
import sys
import argparse
from pathlib import Path
import fnmatch
def search_files(search_path, file_pattern, case_sensitive=False):
"""按文件名模式搜索文件"""
results = []
search_path = Path(search_path)
if not search_path.exists():
print(f"错误: 路径 '{search_path}' 不存在")
return results
for root, dirs, files in os.walk(search_path):
for filename in files:
if case_sensitive:
if fnmatch.fnmatch(filename, file_pattern):
results.append(os.path.join(root, filename))
else:
if fnmatch.fnmatch(filename.lower(), file_pattern.lower()):
results.append(os.path.join(root, filename))
return results
def format_size(size_bytes):
"""格式化文件大小"""
for unit in ['B', 'KB', 'MB', 'GB']:
if size_bytes < 1024:
return f"{size_bytes:.1f} {unit}"
size_bytes /= 1024
return f"{size_bytes:.1f} TB"
def main():
parser = argparse.ArgumentParser(description='按名称检索本地文件')
parser.add_argument('-n', '--name', required=True, help='文件名(支持通配符 * 和 ?)')
parser.add_argument('-p', '--path', default='.', help='搜索路径(默认当前目录)')
parser.add_argument('-c', '--case-sensitive', action='store_true', help='区分大小写')
parser.add_argument('--max-results', type=int, default=0, help='最大显示结果数(0表示全部)')
args = parser.parse_args()
print(f"正在搜索: {args.name}")
print(f"搜索路径: {os.path.abspath(args.path)}")
print("-" * 50)
# 执行搜索
results = search_files(args.path, args.name, args.case_sensitive)
if not results:
print("未找到匹配的文件。")
return
# 限制显示数量
display_results = results[:args.max_results] if args.max_results > 0 else results
for filepath in display_results:
try:
stat_info = os.stat(filepath)
size = format_size(stat_info.st_size)
modified = datetime.fromtimestamp(stat_info.st_mtime).strftime('%Y-%m-%d %H:%M')
print(f"📄 {filepath}")
print(f" 大小: {size} | 修改时间: {modified}")
except:
print(f"📄 {filepath}")
if args.max_results > 0 and len(results) > args.max_results:
print(f"\n... 还有 {len(results) - args.max_results} 个结果未显示")
print(f"\n共找到 {len(results)} 个文件")
if __name__ == "__main__":
from datetime import datetime
main()
使用方式:
# 基本搜索 python find_file.py -n "*.txt" -p "/home/user" # 不区分大小写搜索 python find_file.py -n "report" -p "D:\Documents" # 显示前10个结果 python find_file.py -n "*.pdf" -p "C:\Users" --max-results 10
增强版 Python 脚本(带 GUI)
如果需要图形界面,可以使用 tkinter:
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import os
from pathlib import Path
import fnmatch
class FileSearchGUI:
def __init__(self, root):
self.root = root
self.root.title("文件搜索工具")
self.root.geometry("700x500")
# 创建界面元素
self.setup_ui()
def setup_ui(self):
# 搜索设置区域
frame = ttk.LabelFrame(self.root, text="搜索设置", padding=10)
frame.pack(fill="x", padx=10, pady=5)
# 文件名
ttk.Label(frame, text="文件名:").grid(row=0, column=0, sticky="w")
self.name_entry = ttk.Entry(frame, width=30)
self.name_entry.grid(row=0, column=1, padx=5, sticky="we")
ttk.Label(frame, text="(支持 * 和 ? 通配符)").grid(row=0, column=2, sticky="w")
# 搜索路径
ttk.Label(frame, text="搜索路径:").grid(row=1, column=0, sticky="w", pady=5)
self.path_var = tk.StringVar(value=os.getcwd())
self.path_entry = ttk.Entry(frame, textvariable=self.path_var, width=50)
self.path_entry.grid(row=1, column=1, padx=5, pady=5, sticky="we")
ttk.Button(frame, text="浏览...", command=self.browse_folder).grid(row=1, column=2)
# 搜索按钮
button_frame = ttk.Frame(self.root)
button_frame.pack(fill="x", padx=10, pady=5)
ttk.Button(button_frame, text="开始搜索", command=self.search_files).pack(side="left", padx=5)
ttk.Button(button_frame, text="清空结果", command=self.clear_results).pack(side="left")
self.status_label = ttk.Label(button_frame, text="")
self.status_label.pack(side="right")
# 结果显示区域
result_frame = ttk.LabelFrame(self.root, text="搜索结果", padding=5)
result_frame.pack(fill="both", expand=True, padx=10, pady=5)
# 创建树形视图
columns = ("文件名", "路径", "大小", "修改时间")
self.tree = ttk.Treeview(result_frame, columns=columns, show="headings", height=15)
# 设置列
self.tree.heading("文件名", text="文件名")
self.tree.heading("路径", text="路径")
self.tree.heading("大小", text="大小")
self.tree.heading("修改时间", text="修改时间")
self.tree.column("文件名", width=150)
self.tree.column("路径", width=300)
self.tree.column("大小", width=80)
self.tree.column("修改时间", width=150)
# 滚动条
scrollbar = ttk.Scrollbar(result_frame, orient="vertical", command=self.tree.yview)
self.tree.configure(yscrollcommand=scrollbar.set)
self.tree.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
def browse_folder(self):
folder = filedialog.askdirectory(initialdir=self.path_var.get())
if folder:
self.path_var.set(folder)
def format_size(self, size):
for unit in ['B', 'KB', 'MB', 'GB']:
if size < 1024:
return f"{size:.1f} {unit}"
size /= 1024
return f"{size:.1f} TB"
def search_files(self):
pattern = self.name_entry.get().strip()
search_path = self.path_var.get().strip()
if not pattern:
messagebox.showwarning("警告", "请输入文件名")
return
# 清空之前的结果
self.clear_results()
self.status_label.config(text="正在搜索...")
self.root.update()
count = 0
try:
for root, dirs, files in os.walk(search_path):
for filename in files:
if fnmatch.fnmatch(filename, pattern):
filepath = os.path.join(root, filename)
try:
stat = os.stat(filepath)
size = self.format_size(stat.st_size)
from datetime import datetime
modified = datetime.fromtimestamp(stat.st_mtime).strftime('%Y-%m-%d %H:%M')
self.tree.insert("", "end", values=(
filename,
root,
size,
modified
))
count += 1
except:
continue
except Exception as e:
messagebox.showerror("错误", f"搜索过程中发生错误: {str(e)}")
self.status_label.config(text=f"搜索完成,找到 {count} 个文件")
def clear_results(self):
self.tree.delete(*self.tree.get_children())
self.status_label.config(text="")
if __name__ == "__main__":
root = tk.Tk()
app = FileSearchGUI(root)
root.mainloop()
使用建议
- 命令行快速搜索:使用 PowerShell(Windows)或 Shell(Linux/macOS)
- 跨平台开发:使用 Python 版本,可在任何操作系统运行
- 日常使用:GUI 版本(Python tkinter)适合不熟悉命令行的用户
- 高级功能:可以扩展 Python 版本,添加正则表达式搜索、文件内容搜索等功能
这些脚本都支持通配符搜索(如 *.txt、report*),可以根据实际需求选择合适的版本。
版权声明: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直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播