gpt4 book ai didi

Bash:所有子文件夹上的 Tab 文件名完成

转载 作者:行者123 更新时间:2023-12-05 04:12:27 25 4
gpt4 key购买 nike

有什么方法可以配置 bash,以便点击 Tab 键展开文件名将搜索所有子文件夹以及当前文件夹?

例如我的文件夹结构

readme.txt
colors/blue.txt
colors/red.txt
people/roger.txt

我要less r<tab> (或者用 less **/r<tab> 展开以显示所有以 r 开头的扩展选项:

readme.txt colors/red.txt people/roger.txt

最佳答案

假设如下情况,包括两级子目录:

.
├── colors
│   ├── blue.txt
│   └── red.txt
├── completion.bash
├── people
│   ├── rdir
│   ├── roger.txt
│   └── subdir
│   └── rhino.txt
└── readme.txt

你可以通过这个函数得到你想要的那种补全:

_comp_less () {
# Store current globstar setting and set globstar if necessary
local glob_flag
if shopt -q globstar; then
glob_flag=0
else
glob_flag=1
shopt -s globstar
fi

# $2 is the word being completed
local cur=$2

# Loop over all files and directories in the current and all subdirectories
local fname
for fname in **/"$cur"*; do

# Only add files
if [[ -f "$fname" ]]; then
COMPREPLY+=("$fname")
fi
done

# Set globstar back to previous value if necessary
if (( glob_flag == 1 )); then
shopt -u globstar
fi

return 0
}

它检查 globstar shell 选项并在必要时设置它(如果未设置为开始则再次取消设置),然后使用 **/"$cur"* glob 获取所有完成当前单词的文件和目录(包括子目录),最后过滤掉目录名。

函数可以放在你的.bashrc中,以及将其用于 less 的说明:

complete -F _comp_less less

现在,less r<tab>完成如下:

$ less r
colors/red.txt people/subdir/rhino.txt
people/roger.txt readme.txt

关于Bash:所有子文件夹上的 Tab 文件名完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40333916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com