Shell 拾趣系列 - 文件查找预览

6,097 阅读2分钟

一个致力于实用且有趣的 Shell 系列 🌝

Shell “实趣”系列的第二篇来啦。

前言

今天介绍一个十分强大的 CLI 模糊查询工具命令 - fzf,由于 fzf 是一个通用的查询命令,基于 fzf 命令可以衍生出许许多多实用的命令。
image.png

(p.s 进入 github.com/junegunn/fz… 中获取更多信息)

使用

首先,我们需要安装 fzf 命令如下:

brew install fzf


然后我们可以直接在命行中快速体验了。示意如下,可以通过 fzf 模糊查找文件如下:
fzf.gif

妙用其一:文件查找

fzf 提供了丰富的布局参数,通过参数美化搜索界面:

alias fzf.w="fzf --height 40% --layout reverse --info inline --border \
    --preview 'file {}' --preview-window down:1:noborder \
    --color 'fg:#bbccdd,fg+:#ddeeff,bg:#334455,preview-bg:#223344,border:#778899'"


fzf-w.gif

妙用其二:文件预览

请提前安装 bat 命令:github.com/sharkdp/bat


为了可以在终端使代码着色,请提前安装 bat。

alias fzf.p="fzf --preview 'bat --style=numbers --color=always --line-range :500 {}'"

fzf-p.gif

可以简化一下,下次只要输入 f 即可:

alias f="fzf.p"

妙用其三:Git 分支查找/Git Commit 查找

以此类推,可以通过 fzf 做到时髦的切换分支、或搜寻对应的 commit 内容。

_fzf_gco() {
  git branch | fzf | sed -e "s/* //g" | xargs -I {} git checkout {}
}
_fzf_gcs() {
  git log --oneline | fzf | grep -o -E "^[0-9a-z]+" | xargs -I {} git show {}
}


_fzf_gco.gif

妙用其四:文件结构预览

在 macOS 系统下提前安装 fd 命令:github.com/sharkdp/fd


还可以预览文件夹结构 :)

_fzf_tree() {
  fd --type d | fzf | xargs -I {} tree -C {}
}

妙用无穷

正因为 fzf 是一个如此通用的命令,我们可以机智的结合其它 shell 命令玩出许多花样。

fzf | xargs ls -laG


搜索文件后用 vim 打开:

vim `fzf`


搜索进程:

ps aux | fzf


搜索 bash 历史命令并拷贝到粘贴板:

history | fzf | sed -E "s/[[:space:]]*[[:digit:]]+[[:space:]]*//g" | pbcopy

搜索语法

这里粘贴一下 fzf 文档中的搜索语法,请配合使用。

TokenMatch typeDescription
sbtrktfuzzy-matchItems that match sbtrkt
'wildexact-match (quoted)Items that include wild
^musicprefix-exact-matchItems that start with music
.mp3$suffix-exact-matchItems that end with .mp3
!fireinverse-exact-matchItems that do not include fire
!^musicinverse-prefix-exact-matchItems that do not start with music
!.mp3$inverse-suffix-exact-matchItems that do not end with .mp3


如果想要知道更多的 fzf 选项,可以运行 man fzf 获取详细信息。(比如 -m 命令代表多选)

小结

Anyway,本文介绍的 fzf 对于终端重度用户来说,应该也算是眼前一亮的命令了。同时,它在 Github 上也有 32k+ 的 star,怎么说也值得大家花点心思研究研究。