📌
rg と fd の使い方ガイド
ターミナルでVS Code風の検索を実現する2つのツール
課題
メモやノートなどを全てローカルPCのファイルに記述しgitで管理している。
それを毎回cursorで閲覧していると開発用のものとごっちゃになってしまって煩雑である。かといって、obsidianなどの新しいツールを増やすのは思想に反していた。
交通機関が多く集まり、人の乗り降りが多い所。鉄道の終点。空港で、種々の事務のための施設が集まっている場所。
概要
-
rg
(ripgrep) = VS CodeのCtrl+Shift+F(全ファイル内検索) -
fd
= VS CodeのCtrl+P(ファイル名検索)
インストール
# macOS (Homebrew)
brew install ripgrep fd
# Ubuntu/Debian
sudo apt install ripgrep fd-find
# Arch Linux
sudo pacman -S ripgrep fd
rg (ripgrep) - ファイル内容検索
基本的な使い方
# 基本検索
rg "検索文字列"
# 大文字小文字を区別しない
rg -i "hello"
# 行番号を表示
rg -n "function"
# 検索結果のファイル名のみ表示
rg -l "TODO"
ファイルタイプ指定
# Python ファイルのみ検索
rg "def main" --type py
# JavaScript/TypeScript ファイルのみ
rg "console.log" --type js
# Markdown ファイルのみ
rg "# 見出し" --type md
# 利用可能なファイルタイプを確認
rg --type-list
除外設定
# 特定のディレクトリを除外
rg "検索文字列" -g '!node_modules'
# 特定のファイルタイプを除外
rg "検索文字列" -t '!js'
# 隠しファイルも含めて検索
rg "検索文字列" --hidden
正規表現
# 正規表現で検索
rg "\b\d{3}-\d{3}-\d{4}\b" # 電話番号パターン
# 単語境界で検索
rg "\bclass\b"
# OR検索
rg "error|warning|fail"
実用例
# TODOコメントを探す
rg "TODO|FIXME|HACK"
# 関数定義を探す
rg "def |function "
# インポート文を探す
rg "import|require"
# 設定ファイルからデータベース関連を検索
rg "database|db_" --type json --type yaml
fd - ファイル名/パス検索
基本的な使い方
# ファイル名で検索
fd "config"
# 大文字小文字を区別しない
fd -i "CONFIG"
# 完全一致
fd "^config$"
# 拡張子で絞り込み
fd . --extension py
fd . -e js
ファイルタイプ指定
# ディレクトリのみ検索
fd . --type d
# ファイルのみ検索
fd . --type f
# 実行可能ファイルのみ
fd . --type x
# シンボリックリンクのみ
fd . --type l
除外設定
# 隠しファイルも含める
fd "config" --hidden
# 特定のディレクトリを除外
fd "test" --exclude node_modules
# .gitignoreを無視
fd "config" --no-ignore
実用例
# 設定ファイルを探す
fd "config|settings" -e json -e yaml -e toml
# テストファイルを探す
fd "test" -e py -e js
# ドキュメントファイルを探す
fd "readme|doc" -e md -e txt
# 特定のプロジェクトファイルを探す
fd "package.json|Cargo.toml|requirements.txt"
組み合わせて使う
ファイルを見つけてから内容検索
# Python ファイルを見つけて、その中から特定の関数を検索
fd . -e py | xargs rg "def main"
# 設定ファイルを見つけて、データベース設定を検索
fd "config" -e json | xargs rg "database"
# テストファイルを見つけて、特定のテストケースを検索
fd "test" -e py | xargs rg "test_user"
エディターで開く
# 検索結果をVS Codeで開く
rg -l "TODO" | xargs code
# ファイル検索結果をVimで開く
fd "config" -e json | xargs vim
便利なエイリアス設定
.bashrc
や .zshrc
に追加:
# よく使う検索パターン
alias todo="rg 'TODO|FIXME|HACK'"
alias pydef="rg 'def |class ' --type py"
alias jslog="rg 'console\.' --type js"
# ファイル検索
alias fconfig="fd 'config|settings'"
alias ftest="fd 'test' -e py -e js"
alias fmd="fd . -e md"
VS Code風のワークフロー
1. プロジェクト全体から文字列検索 (Ctrl+Shift+F相当)
rg "検索したい文字列"
2. ファイル名で素早く検索 (Ctrl+P相当)
fd "ファイル名"
3. 特定のファイルタイプで絞り込み検索
rg "関数名" --type py
fd "component" -e js -e ts
4. 検索結果を直接エディターで開く
# 該当ファイルをすべてエディターで開く
rg -l "検索文字列" | xargs code
fd "ファイル名" | xargs code
これらのツールを使うことで、VS Codeを開かずにターミナルだけで効率的な検索作業が可能になります。
Discussion