pecoを使って動的にgrepする
動的にgrepを行って絞り込みが出来るpecoというツールを教わったので使ってみました。候補の文字列を動的に絞り込めるのでとても便利なツールです。pecoはなんとGo言語で動きます(pecoの元になったpercolはpython製)。
インストールはMacならHomebrewで一発(環境はMac OS X 10.9.4)。
brew tap peco/peco brew install peco
いくつかpecoを使ったコマンドを定義してみました。
pecoをコマンドラインのどの文脈でも使う
alias -g P='| peco' alias -g Px='| peco | xargs '
PやPxとうつとコマンドラインの途中でも使えます。あるコマンドc1の結果をpecoで絞り込み、その結果をコマンドc2で使いたいときは「c1 Px c2」で出来ます。例えば、「ls Px file」でディレクトリ下のファイルを絞り込み、その選択結果の詳細を表示します。
pecoの結果をクリップボードにコピー
function p(){ $@ | peco | pbcopy }
コマンドの結果を絞り込んで選択するとその結果をクリップボードにコピーします。
例えば、「p ls」と打つと、現在のディレクトリのファイル一覧を表示し、選択した結果をクリップボードにコピーします。
ファイルを探す
alias pls='ls -a | peco' alias pfind='find -L . -name "*" | peco'
ファイルの内部を探す
function pcat(){ cat -n $@ | peco }
「pcat f1 f2 ..」でファイルf1, f2, ...の各行を絞り込み検索します。
コマンドライン履歴検索
function peco-select-history() { local cmd=`history | tail -r | peco | cut -d ' ' -f 1` if [ "${cmd}" != "" ]; then r ${cmd} return 0; fi return -1; } zle -N peco-select-history alias phist='peco-select-history'
phistと打つとコマンドライン履歴の一覧が表示され、絞り込んで選択するとそのコマンドを実行します。
絞り込みcd
過去のディレクトリ移動履歴から候補を選択し、そのディレクトリに移動します。
typeset -U chpwd_functions CD_HISTORY_FILE=${HOME}/.cd_history_file # cd 履歴の記録先ファイル function chpwd_record_history() { echo $PWD >> ${CD_HISTORY_FILE} } chpwd_functions=($chpwd_functions chpwd_record_history) function peco_get_destination_from_history() { sort ${CD_HISTORY_FILE} | uniq -c | sort -r | \ sed -e 's/^[ ]*[0-9]*[ ]*//' | \ sed -e s"/^${HOME//\//\\/}/~/" | \ peco | xargs echo } function peco_cd_history() { local destination=$(peco_get_destination_from_history) if [ "${destination}" != "" ]; then echo "${destination}" cd ${destination/#\~/${HOME}} zle -N reset-prompt return 0; fi return -1; } zle -N peco_cd_history alias pcd='peco_cd_history' function peco_insert_history() { local destination=$(peco_get_destination_from_history) if [ $? -eq 0 ]; then local new_left="${LBUFFER} ${destination} " BUFFER=${new_left}${RBUFFER} CURSOR=${#new_left} fi zle -N reset-prompt } zle -N peco_insert_history alias pins='peco_insert_history'
参考:http://stillpedant.hatenablog.com/entry/percol-cd-history
Gitのブランチを扱う
function br_fmt(){ git branch -a | peco | xargs echo | sed -e 's/\*//' | sed -e 's/remotes\/origin\///' }
ブランチをpecoで選択し、その結果を整形して返します(整形は余分な空白と*を取り除き、「remotes/origin/」を取り除きます)。
僕は下記のようにpushやpull, checkoutの時にブランチを絞り込んで使ってます。
alias pgco='br_fmt | xargs git checkout' alias pgcob='br_fmt | xargs git checkout -b' alias pgpl='br_fmt | xargs git pull origin' alias pgps='br_fmt | xargs git push origin' alias pgb='git branch -a | peco'
とても便利なツールですので、是非使ってみてください!