用脚本实现快捷系统搜索

wen 实用脚本 2

本文目录导读:

用脚本实现快捷系统搜索

  1. Windows 系统
  2. macOS 系统
  3. Linux 系统
  4. 跨平台推荐方案
  5. 安装与使用建议
  6. 进阶配置

Windows 系统

使用 AutoHotkey 创建全局快捷键

; 一键搜索脚本 - 保存为 QuickSearch.ahk
; Win+Space 打开搜索
#Space::
{
    Send("#s")  ; 打开Windows搜索
    Sleep(100)
    Send("^a")  ; 全选已有文本
    Sleep(50)
    Send("{Backspace}")  ; 清空
}
return
; Ctrl+Shift+F 搜索选中文本
^+F::
{
    ClipboardBackup := ClipboardAll()
    Send("^c")
    ClipWait(1)
    SearchText := Clipboard
    Run("https://www.google.com/search?q=" . UrlEncode(SearchText))
    Clipboard := ClipboardBackup
}
return
; 快速搜索特定网站 - 输入 !! + 关键词
#Persistent
~>::
{
    Input, SearchQuery, V, {Enter}
    if (SearchQuery != "") {
        Run("https://www.baidu.com/s?wd=" . UrlEncode(SearchQuery))
    }
}
return
UrlEncode(str) {
    Return UriEncode(str)
}

PowerShell 脚本 - 系统搜索增强

# QuickSearch.ps1 - 现代系统搜索脚本
param(
    [string]$Query = "",
    [string]$Path = "",
    [switch]$File,
    [switch]$Folder,
    [switch]$App
)
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$configPath = Join-Path $scriptDir "searchConfig.json"
# 默认配置
$config = @{
    defaultSearch = "both"  # file, folder, app, both
    maxResults = 20
    excludePaths = @("C:\Windows", "C:\Program Files\Temp")
    searchEngines = @{
        web = "https://www.google.com/search?q="
        images = "https://images.google.com/images?q="
        videos = "https://www.youtube.com/results?search_query="
    }
}
# 加载配置
if (Test-Path $configPath) {
    $config = Get-Content $configPath | ConvertFrom-Json
}
# 文件搜索函数
function Search-Files {
    param($query, $path)
    $results = Get-ChildItem -Path $path -Recurse -ErrorAction SilentlyContinue |
        Where-Object { $_.Name -like "*$query*" -and !$_.PSIsContainer } |
        Select-Object -First $config.maxResults
    return $results
}
# 文件夹搜索
function Search-Folders {
    param($query, $path)
    $results = Get-ChildItem -Path $path -Recurse -ErrorAction SilentlyContinue |
        Where-Object { $_.Name -like "*$query*" -and $_.PSIsContainer } |
        Select-Object -First $config.maxResults
    return $results
}
# 应用搜索
function Search-Apps {
    param($query)
    $results = Get-StartApps | 
        Where-Object { $_.Name -like "*$query*" } |
        Select-Object -First $config.maxResults
    return $results
}
# 主搜索逻辑
$searchResults = @()
if ($Query) {
    $searchPaths = @($env:USERPROFILE, "D:\", "E:\")
    if ($File -or $config.defaultSearch -eq "file") {
        foreach ($path in $searchPaths) {
            $searchResults += Search-Files -query $Query -path $path
        }
    }
    if ($Folder -or $config.defaultSearch -eq "folder") {
        foreach ($path in $searchPaths) {
            $searchResults += Search-Folders -query $Query -path $path
        }
    }
    if ($App -or $config.defaultSearch -eq "app") {
        $searchResults += Search-Apps -query $Query
    }
    # 显示结果
    if ($searchResults.Count -gt 0) {
        Write-Host "`n搜索结果 ($($searchResults.Count) 项):" -ForegroundColor Green
        $searchResults | ForEach-Object { Write-Host "  $($_.FullName)" }
    } else {
        Write-Host "`n未找到匹配项" -ForegroundColor Yellow
    }
}

macOS 系统

Alfred 风格工作流脚本

#!/bin/bash
# mac_search.sh - macOS 智能搜索脚本
# 搜索类型选择
QUERY="$1"
SEARCH_TYPE="${2:-all}"
# 配置文件
CONFIG_FILE="$HOME/.quick_search_config"
# 默认搜索引擎
DEFAULT_SEARCH="https://www.google.com/search?q="
BAIDU_SEARCH="https://www.baidu.com/s?wd="
BING_SEARCH="https://www.bing.com/search?q="
# 搜索函数
search_files() {
    local query="$1"
    mdfind "kMDItemDisplayName == '*${query}*'" -onlyin ~/
}
search_apps() {
    local query="$1"
    mdfind "kMDItemKind == 'Application' && kMDItemDisplayName == '*${query}*'"
}
search_web() {
    local query="$1"
    local engine="${2:-google}"
    case "$engine" in
        google) open "${DEFAULT_SEARCH}${query}" ;;
        baidu) open "${BAIDU_SEARCH}${query}" ;;
        bing) open "${BING_SEARCH}${query}" ;;
        *) open "${DEFAULT_SEARCH}${query}" ;;
    esac
}
# 智能搜索主逻辑
case "$SEARCH_TYPE" in
    file)
        search_files "$QUERY"
        ;;
    app)
        search_apps "$QUERY"
        ;;
    web)
        search_web "$QUERY" "google"
        ;;
    all)
        echo "🔍 搜索文件..."
        search_files "$QUERY" | head -20
        echo "📱 搜索应用..."
        search_apps "$QUERY" | head -10
        echo "🌐 网页搜索..."
        search_web "$QUERY"
        ;;
esac

使用 Automator 创建服务

-- 保存为 QuickSearch.applescript
on run {input, parameters}
    set searchQuery to text returned of (display dialog "请输入搜索内容:" default answer "" buttons {"取消", "搜索"} default button "搜索")
    if searchQuery is not "" then
        -- 本地文件搜索
        set fileResults to do shell script "mdfind -onlyin ~/ " & quoted form of searchQuery & " | head -20"
        -- 显示结果
        set resultList to paragraphs of fileResults
        set chosenResult to choose from list resultList with title "搜索结果" with prompt "选择要打开的文件:"
        if chosenResult is not false then
            set item (item 1 of chosenResult) to POSIX file
            tell application "Finder"
                open item
            end tell
        end if
    end if
end run

Linux 系统

Unity/GNOME 搜索增强脚本

#!/bin/bash
# gnome_search.sh - GNOME 桌面搜索增强
# 配置文件
CONFIG_DIR="$HOME/.config/quicksearch"
mkdir -p "$CONFIG_DIR"
# 搜索配置
SEARCH_DELAY=${DELAY:-0.5}
MAX_RESULTS=${MAX_RESULTS:-15}
# 搜索函数
search_local() {
    local query="$1"
    locate "$query" | head -n "$MAX_RESULTS"
}
search_apps() {
    local query="$1"
    command -v apt-cache >/dev/null 2>&1 && apt-cache search "$query" | head -10
}
search_kde() {
    local query="$1"
    # KDE Baloo 搜索
    baloosearch "$query" | head -n "$MAX_RESULTS"
}
# 统一搜索界面
search_all() {
    local query="$1"
    echo "=== 文件搜索 ==="
    search_local "$query"
    echo "=== 应用搜索 ==="
    search_apps "$query"
    if command -v baloosearch >/dev/null 2>&1; then
        echo "=== KDE 桌面搜索 ==="
        search_kde "$query"
    fi
}
# 快捷键绑定 (添加到 ~/.config/hotkeys.conf)
setup_hotkeys() {
    cat > "$CONFIG_DIR/hotkeys.conf" << EOF
# 快捷键配置
# 格式: 快捷键 | 搜索类型 | 搜索路径
Ctrl+Shift+F | all | ~/Documents
Ctrl+Shift+A | apps | /
Ctrl+Shift+W | web | ~
EOF
    echo "快捷键配置已创建: $CONFIG_DIR/hotkeys.conf"
}
# 主程序
case "${1:-all}" in
    file) search_local "$2" ;;
    apps) search_apps "$2" ;;
    kde) search_kde "$2" ;;
    setup) setup_hotkeys ;;
    *) search_all "$2" ;;
esac

i3wm 脚本 - 浮动搜索窗口

#!/bin/bash
# i3_quicksearch.sh - i3窗口管理器专用搜索
# 创建浮动搜索窗口
SEARCH_TERM=$(i3-input | xargs)
# 多种搜索方式
case "$SEARCH_TERM" in
    \!*) 
        # 网络搜索
        QUERY=$(echo "$SEARCH_TERM" | cut -c2-)
        firefox "https://www.google.com/search?q=$QUERY"
        ;;
    \#*)
        # 文件搜索
        QUERY=$(echo "$SEARCH_TERM" | cut -c2-)
        kitty -e bash -c "find ~ -name '*$QUERY*' 2>/dev/null | less"
        ;;
    *)
        # 默认应用搜索
        rofi -show drun -theme search -filter "$SEARCH_TERM"
        ;;
esac

跨平台推荐方案

使用 Python 实现统一搜索

#!/usr/bin/env python3
# unified_search.py - 跨平台统一搜索脚本
import os
import sys
import subprocess
import json
from pathlib import Path
class QuickSearch:
    def __init__(self):
        self.config_path = Path.home() / ".quick_search_config"
        self.config = self.load_config()
    def load_config(self):
        """加载配置"""
        if self.config_path.exists():
            with open(self.config_path, 'r') as f:
                return json.load(f)
        return {
            "max_results": 20,
            "search_paths": ["~", "/mnt/data"],
            "engines": {
                "web": "https://www.google.com/search?q=",
                "images": "https://images.google.com/images?q="
            }
        }
    def platform_search(self, query, search_type="files"):
        """平台对应的搜索实现"""
        platform = sys.platform
        if platform == "win32":
            return self.windows_search(query, search_type)
        elif platform == "darwin":
            return self.macos_search(query, search_type)
        elif platform.startswith("linux"):
            return self.linux_search(query, search_type)
        else:
            raise NotImplementedError(f"Unsupported platform: {platform}")
    def windows_search(self, query, search_type):
        """Windows 搜索"""
        if search_type == "files":
            cmd = f'Get-ChildItem -Path $env:USERPROFILE -Recurse | Where-Object {{ $_.Name -like "*{query}*" }} | Select-Object -First {self.config["max_results"]}'
            subprocess.run(["powershell", "-Command", cmd])
        elif search_type == "apps":
            subprocess.run(["powershell", "-Command", f'Get-StartApps | Where-Object {{ $_.Name -like "*{query}*" }}'])
    def macos_search(self, query, search_type):
        """macOS 搜索"""
        if search_type == "files":
            subprocess.run(["mdfind", "-onlyin", "~/", query])
        elif search_type == "apps":
            mdfind_cmd = f'mdfind "kMDItemKind == \'Application\' && kMDItemDisplayName == \'*{query}*\'"'
            subprocess.run(["bash", "-c", mdfind_cmd])
    def linux_search(self, query, search_type):
        """Linux 搜索"""
        if subprocess.run(["which", "locate"], capture_output=True).returncode == 0:
            if search_type == "files":
                subprocess.run(["locate", "-i", query])
        else:
            print("请安装 mlocate 或 plocate 包")
    def web_search(self, query, engine="web"):
        """网页搜索"""
        url = self.config["engines"][engine] + query
        subprocess.run(["xdg-open", url]) if sys.platform != "win32" else subprocess.run(["start", url])
    def run(self):
        """主运行函数"""
        if len(sys.argv) < 2:
            query = input("请输入搜索内容: ")
        else:
            query = sys.argv[1]
        print(f"🔍 正在搜索: {query}")
        self.platform_search(query)
        # 同时打开网络搜索
        self.web_search(query)
if __name__ == "__main__":
    searcher = QuickSearch()
    searcher.run()

安装与使用建议

  1. Windows 用户:推荐使用 AutoHotkey 脚本,配合 Everything 工具效果更佳
  2. macOS 用户:推荐使用 Alfred 或 Raycast 替代脚本方案
  3. Linux 用户:根据桌面环境选择(GNOME 使用 Search Provider,KDE 使用 Baloo)
  4. 跨平台:使用 Python 脚本可以获得统一的体验

进阶配置

  1. 添加模糊搜索功能(fzf 工具)
  2. 实现搜索历史记录
  3. 集成 OCR 搜索(提取图片中的文字)
  4. 添加文件预览功能

选择合适的脚本并根据自己的需求调整配置,就能打造出高效的系统搜索工具。

抱歉,评论功能暂时关闭!