万物皆可 fzf

- hikerpig
#zsh#tip#fzf#terminal

fzf 是一个速度和适用范围都极好的模糊搜索工具,借助 UNIX 管道,可以接入日常几乎所有终端 CLI 操作中,对所有的 list 都能有美好的可交互式模糊过滤体验。

It's an interactive Unix filter for command-line that can be used with any list; files, command history, processes, hostnames, bookmarks, git commits, etc.

基础的教程已经一搜一大把了,我推荐:

以下为不那么常用的技巧补充。

一些技巧

使用 -m 参数支持多选

cat $(fzf -m)

然后就可以使用 tab 或者 shift+tab 实现多选。在使用 cat/rm 等命令时很好用。

使用 ** 作为 trigger

unset **<Tab>
unalias **<Tab>

善用 --preview

交互式地选择 git branch。

# git interactive checkout
gcb() {
  result=$(git branch -a --color=always | grep -v '/HEAD\s' | sort |
    fzf --height 50% --border --ansi --tac --preview-window right:70% \
      --preview 'git log --oneline --graph --date=short --pretty="format:%C(auto)%cd %h%d %s" $(sed s/^..// <<< {} | cut -d" " -f1) | head -'$LINES |
    sed 's/^..//' | cut -d' ' -f1)

  if [[ $result != "" ]]; then
    if [[ $result == remotes/* ]]; then
      git checkout --track $(echo $result | sed 's#remotes/##')
    else
      git checkout "$result"
    fi
  fi
}

实用脚本

fzf-tab, 替换 zsh 的默认补全选择菜单

Aloxaf/fzf-tab ,如其自我介绍

Replace zsh's default completion selection menu with fzf!

这个脚本可以将 zsh 的默认 completion 结果转给 fzf 显示(而不是使用 zsh 默认的补全菜单),让你在选择补全结果的时候获得 fzf 加持。

若使用 zimfw 安装,在 .zimrc 内添加:

zmodule Aloxaf/fzf-tab

asciicast

fzf-fasd, 配合 fasd 可代替 z

wookayin/fzf-fasd: 🌸 fzf + fasd integration ,实现了类似 z 这样快速跳转目录的效果, z<Tab> 后使用 fzf 选择最近进入过的目录。

其他零零散散

bindkey | fzf # 搜索当前 shell 里所有绑定了的快捷键

fzf --preview "bat {} --color=always" # 快速预览当前以及子目录下文件内容,不在乎颜色的话 bat 可以换成 cat

cd $(find . -type d | fzf) # 可选择进入某个深层子目录
cd $(fd --type directory | fzf) # 与上面类似,不过使用更便捷的 fd

在 vim 中使用

使用同一作者写的 vim 插件 fzf.vim

参考文章