如何写一个脚本记忆位置

wen 实用脚本 1

本文目录导读:

如何写一个脚本记忆位置

  1. 🎯 命令行历史搜索
  2. 快速书签工具
  3. 📁 Python 脚本(跨平台)
  4. 🚀 智能位置记忆(高级)
  5. 🔧 使用方法

我来介绍几种记忆位置的脚本方案,从简单到复杂:

🎯 命令行历史搜索

最简单的方式,记录经常使用的命令:

# 在 ~/.bashrc 或 ~/.zshrc 中添加
# 搜索历史命令
function find_cmd() {
    history | grep -i "$1" | tail -20
}
# 记住当前位置
function remember() {
    echo "$PWD" >> ~/.locations
    echo "📍 已记住: $PWD"
}
# 跳转到记住的位置
function goto() {
    if [ -z "$1" ]; then
        # 显示所有位置
        cat -n ~/.locations
    else
        cd "$(sed -n "${1}p" ~/.locations)"
    fi
}

快速书签工具

# ~/.bashrc 或 ~/.zshrc 中添加
BOOKMARKS_FILE="$HOME/.bookmarks"
# 添加书签
bookmark() {
    local name="$1"
    local dir="$PWD"
    if [ -z "$name" ]; then
        echo "用法: bookmark 名称"
        return 1
    fi
    echo "$name=$dir" >> "$BOOKMARKS_FILE"
    echo "✅ 已添加书签: $name -> $dir"
}
# 跳转到书签
bm() {
    if [ -z "$1" ]; then
        # 显示所有书签
        while IFS='=' read -r name dir; do
            echo "📌 $name -> $dir"
        done < "$BOOKMARKS_FILE"
        return 0
    fi
    local dir=$(grep "^$1=" "$BOOKMARKS_FILE" | cut -d'=' -f2)
    if [ -n "$dir" ]; then
        cd "$dir"
        echo "🚀 已跳转到: $dir"
    else
        echo "❌ 未找到书签: $1"
    fi
}
# 删除书签
bm_del() {
    sed -i "/^$1=/d" "$BOOKMARKS_FILE"
    echo "🗑️ 已删除书签: $1"
}

📁 Python 脚本(跨平台)

#!/usr/bin/env python3
# location_manager.py
import json
import os
import sys
from pathlib import Path
import subprocess
class LocationManager:
    def __init__(self):
        self.config_file = Path.home() / ".location_manager.json"
        self.locations = self.load()
    def load(self):
        if self.config_file.exists():
            with open(self.config_file, 'r') as f:
                return json.load(f)
        return {}
    def save(self):
        with open(self.config_file, 'w') as f:
            json.dump(self.locations, f, indent=2, ensure_ascii=False)
    def add(self, name, path=None):
        if path is None:
            path = os.getcwd()
        path = os.path.abspath(path)
        self.locations[name] = path
        self.save()
        print(f"✅ 已添加: {name} -> {path}")
    def list_all(self):
        print("📁 记忆的位置:")
        for i, (name, path) in enumerate(self.locations.items(), 1):
            is_dir = os.path.isdir(path)
            is_file = os.path.isfile(path)
            type_icon = "📂" if is_dir else "📄" if is_file else "❓"
            print(f"  {i}. {type_icon} {name} -> {path}")
    def goto(self, name):
        if name in self.locations:
            path = self.locations[name]
            if os.path.exists(path):
                os.system(f'cd "{path}" && exec $SHELL')
            else:
                print(f"⚠️ 路径不存在: {path}")
                if input("是否删除该记录?(y/n): ").lower() == 'y':
                    del self.locations[name]
                    self.save()
        else:
            print(f"❌ 未找到: {name}")
    def search(self, keyword):
        print(f"🔍 搜索 [{keyword}] 的结果:")
        for name, path in self.locations.items():
            if keyword.lower() in name.lower() or keyword.lower() in path.lower():
                type_icon = "📂" if os.path.isdir(path) else "📄"
                print(f"  {type_icon} {name} -> {path}")
    def remove(self, name):
        if name in self.locations:
            del self.locations[name]
            self.save()
            print(f"🗑️ 已删除: {name}")
        else:
            print(f"❌ 未找到: {name}")
    def backup(self, backup_file):
        with open(backup_file, 'w') as f:
            json.dump(self.locations, f, indent=2)
        print(f"💾 已备份到: {backup_file}")
    def restore(self, backup_file):
        if Path(backup_file).exists():
            with open(backup_file, 'r') as f:
                self.locations = json.load(f)
            self.save()
            print(f"♻️ 已恢复数据")
        else:
            print(f"❌ 备份文件不存在: {backup_file}")
def main():
    lm = LocationManager()
    if len(sys.argv) < 2:
        lm.list_all()
        return
    cmd = sys.argv[1]
    if cmd == "add":
        name = sys.argv[2]
        path = sys.argv[3] if len(sys.argv) > 3 else None
        lm.add(name, path)
    elif cmd == "list":
        lm.list_all()
    elif cmd == "go":
        if len(sys.argv) < 3:
            print("用法: loc.py go <名称>")
        else:
            lm.goto(sys.argv[2])
    elif cmd == "search":
        keyword = sys.argv[2]
        lm.search(keyword)
    elif cmd == "remove":
        name = sys.argv[2]
        lm.remove(name)
    elif cmd == "backup":
        backup_file = sys.argv[2] if len(sys.argv) > 2 else "locations_backup.json"
        lm.backup(backup_file)
    elif cmd == "restore":
        if len(sys.argv) > 2:
            lm.restore(sys.argv[2])
    elif cmd == "help":
        print("""用法: python loc.py [命令] [参数]
可用命令:
  add <名称> [路径]     - 添加位置
  list                 - 列出所有位置
  go <名称>            - 跳转到位置
  search <关键词>      - 搜索位置
  remove <名称>        - 删除位置
  backup [文件]        - 备份数据
  restore <文件>       - 恢复数据
  help                 - 显示帮助
""")
if __name__ == "__main__":
    main()

🚀 智能位置记忆(高级)

#!/usr/bin/env python3
# smart_locations.py
import json
import os
import time
from pathlib import Path
from collections import defaultdict
class SmartLocationManager:
    def __init__(self):
        self.data_file = Path.home() / ".smart_locations.json"
        self.data = self.load()
    def load(self):
        if self.data_file.exists():
            with open(self.data_file, 'r') as f:
                return json.load(f)
        return {"locations": {}, "history": {}}
    def save(self):
        with open(self.data_file, 'w') as f:
            json.dump(self.data, f, indent=2)
    def add(self, name, path, tags=None, priority=1):
        """添加位置,支持标签和优先级"""
        path = os.path.abspath(path)
        self.data["locations"][name] = {
            "path": path,
            "tags": tags or [],
            "priority": priority,
            "created": time.time(),
            "last_used": time.time(),
            "count": 0
        }
        self.save()
        print(f"✅ 已添加: {name}")
    def goto(self, name):
        """跳转并记录使用频率"""
        if name in self.data["locations"]:
            loc = self.data["locations"][name]
            loc["last_used"] = time.time()
            loc["count"] += 1
            self.save()
            path = loc["path"]
            print(f"🚀 跳转到: {path}")
            # 尝试 cd,如果在 Unix 系统
            if os.name == 'posix':
                os.system(f'cd "{path}" && exec $SHELL')
    def suggest(self, limit=5):
        """根据使用频率和最近使用时间推荐位置"""
        locations = list(self.data["locations"].items())
        # 排序:使用次数多、最近使用过的优先
        locations.sort(key=lambda x: (
            x[1]["count"] > 0,
            x[1]["last_used"],
            x[1]["priority"]
        ), reverse=True)
        print("💡 推荐位置:")
        for name, info in locations[:limit]:
            print(f"  {name} -> {info['path']} (使用{info['count']}次)")
    def search_by_tags(self, *tags):
        """按标签搜索"""
        results = []
        for name, info in self.data["locations"].items():
            if all(tag in info["tags"] for tag in tags):
                results.append((name, info["path"]))
        if results:
            print(f"🏷️ 找到 {len(results)} 个匹配的位置:")
            for name, path in results:
                print(f"  {name} -> {path}")
        else:
            print("❌ 未找到匹配的位置")
    def cleanup_invalid(self):
        """清理不存在的路径"""
        invalid = []
        for name, info in self.data["locations"].items():
            if not os.path.exists(info["path"]):
                invalid.append(name)
        for name in invalid:
            print(f"⚠️ 删除失效位置: {name}")
            del self.data["locations"][name]
        if invalid:
            self.save()
        else:
            print("✨ 所有位置都是有效的")
    def group_by_tag(self):
        """按标签分组显示"""
        groups = defaultdict(list)
        for name, info in self.data["locations"].items():
            for tag in info["tags"]:
                groups[tag].append((name, info["path"]))
        for tag, locations in groups.items():
            print(f"📦 [{tag}]")
            for name, path in locations:
                print(f"  {name} -> {path}")
# 交互式 shell
def interactive_shell():
    sm = SmartLocationManager()
    while True:
        try:
            cmd = input("\n📁 位置管理器> ").strip().split()
            if not cmd:
                continue
            if cmd[0] == "exit" or cmd[0] == "quit":
                break
            elif cmd[0] == "add":
                if len(cmd) >= 2:
                    name = cmd[1]
                    path = cmd[2] if len(cmd) > 2 else os.getcwd()
                    tags = cmd[3:] if len(cmd) > 3 else []
                    sm.add(name, path, tags)
            elif cmd[0] == "list":
                sm.suggest(100)  # 显示所有
            elif cmd[0] == "go":
                if len(cmd) > 1:
                    sm.goto(cmd[1])
            elif cmd[0] == "suggest":
                sm.suggest(5)
            elif cmd[0] == "tags":
                if len(cmd) > 1:
                    sm.search_by_tags(*cmd[1:])
                else:
                    sm.group_by_tag()
            elif cmd[0] == "cleanup":
                sm.cleanup_invalid()
            elif cmd[0] == "help":
                print("""可用命令:
  add <名称> [路径] [标签...]  - 添加位置
  list                        - 列出所有位置
  go <名称>                   - 跳转到位置
  suggest                     - 推荐位置
  tags <标签...>              - 按标签搜索
  cleanup                     - 清理失效位置
  exit/quit                   - 退出
""")
            else:
                print("未知命令,输入 help 查看帮助")
        except KeyboardInterrupt:
            break
        except Exception as e:
            print(f"❌ 错误: {e}")
if __name__ == "__main__":
    interactive_shell()

🔧 使用方法

安装和配置:

# 1. 保存脚本
chmod +x location_manager.py smart_locations.py
cp location_manager.py /usr/local/bin/loc
cp smart_locations.py /usr/local/bin/smart-loc
# 2. 添加到 shell 配置文件 (~/.bashrc 或 ~/.zshrc)
alias loc="python3 /usr/local/bin/loc"
alias slog="python3 /usr/local/bin/smart-loc"

示例使用:

# 添加位置
loc add project ~/Projects/myapp
smart-loc
> add home ~ tags:personal important
# 查看所有位置
loc list
# 跳转
loc go project
# 搜索
loc search project

功能特性:

  1. 基础版:命令行历史 + 书签
  2. 标准版:Python 管理,支持标签
  3. 智能版:使用频率统计、智能推荐、自动清理

选择哪种取决于你的需求:

  • 简单使用:选择命令行版本
  • 跨平台:选 Python 基础版
  • 进阶管理:选智能版

需要我解释具体某个功能或帮你定制吗?

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