gpt4 book ai didi

linux - 在 Linux 终端中的目录之间快速智能导航

转载 作者:太空狗 更新时间:2023-10-29 11:43:50 25 4
gpt4 key购买 nike

我正在处理具有相似结构和子目录的多个项目。层次结构的一个例子是这样的:

enter image description here

其中X是项目名,子目录MainLibsLxMx都是一样的对于不同的项目。 insteding cd'ing betweeing ong paths,我想创建一个别名(或一个简单的命令)来跳转到一个目录(例如:Libs/M2),而不管项目名称和子 -我所在的目录(无论我在 L1L8,还是 project_redproject_yellow,我都想跳转到 M2)。

这很容易通过为单个项目创建别名来实现:

alias goM2='cd /projects/project_red/Libs/M1/M2'

但我不确定如何为所有不同的项目名称执行此操作。我可以创建多个别名,但我想知道是否有一种巧妙的方法可以做到这一点。也许通过解析当前目录来提取项目名称并在末尾添加所需的目标,但我不确定如何执行此操作。

谢谢

最佳答案

如果每个项目的子结构都相同(仅在 LibsMain 下的 libsmains 数量不同 目录),假设您的项目目录位于 $HOME 目录下,并且 projects 目录树如下所示:

projects/|-- project1|   |-- Libs|   |   |-- M1|   |   |-- M2|   |   `-- M3|   `-- Main|       |-- L1|       |-- L2|       `-- L3`-- project2    |-- Libs    |   |-- M1    |   |-- M2    |   `-- M3    `-- Main        |-- L1        |-- L2        `-- L3

a function (declared in your profile or whatever library you use to load during your bash sessions) like the following _go_to_project_dir will do the work as desire.Of course some variables have only an explanatory purpose and a lot of assumptions have been done according to your file system hierarchy.

_go_to_project_dir() {
local projects_HOME="$HOME/projects" # this could be configured as needed

local current_project_dir # this is only an auxiliar variable
printf -v current_project_dir "%b" "${PWD%%/[(Libs)(Main)]*}" # printf -v will store the formated message into the variable following -v option
# '%%' will remove the longest occurrence of the following pattern '/[(Libs)(Main)]*'
# from the 'PWD' variable using pathname expansion

local current_project_name
printf -v current_project_name "%b" "${current_project_dir#${projects_HOME}/}" # '#' will remove shortest occurrence of the following pattern
# '${projects_HOME}/' from the 'current_project_dir' variable
# using pathname expansion

local dir_name="$1" # Directory where you want to go
local project_name="${2-$current_project_name}" # this will store second parameter if provided or 'current_project_name' content elsewhere

local dir_type="${dir_name:0:1}" # this will extract the first character from your directory name but you could select a different length to match your actual pattern names

case ${dir_type} in # here we select the path according to the previously extracted directory type
M )
path_to_go="${projects_HOME}/${project_name}/Libs/${dir_name}"
;;
L )
path_to_go="${projects_HOME}/${project_name}/Main/${dir_name}"
;;
esac

cd "${path_to_go}" # And it's done
}

当然,您可以根据您的目录名称模式以一些不同的方式提取dir_type,但核心思想保持不变。

关于linux - 在 Linux 终端中的目录之间快速智能导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28595192/

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