我有多个目录(例如tom richard harry),它们具有相同的子目录和文件结构。如果我正在处理一个目录中的文件,是否有一种快速或简单的方法来cd到另一个目录中的等效路径?
实施例
pwd=/mystuff/myproject/tom/hobbies/sports/highschool
cd /mystuff/myproject/richard/hobbies/sports/highschool
我希望有一些像cd pwd这样的快捷方式,但是改变tom>理查德在一个命令中。
答案 0 :(得分:11)
以下内容应该有效:
cd ${PWD/tom/richard}
答案 1 :(得分:2)
这样可行:
cd $(pwd | perl -pi -e 's/tom/richard/g;')
答案 2 :(得分:1)
如果你知道你所在的目录(比如存储在$dirname
变量中):
function dirswitch() {
newdir="$1"
cd $(pwd | sed -e "s#/$dirname/#/$newdir/#")
}
这应该处理bash中的工作。因此,如果您在dirname=tom
并且想要切换到harry
:
dirswitch harry
......会做的。
答案 3 :(得分:1)
答案 4 :(得分:1)
一切都取决于你的贝壳......
大多数人使用BASH - 它是标准的Linux shell,但Kornshell与BASH非常相似,并且具有您正在寻找的功能:
$ cd /mystuff/myproject/tom/hobbies/sports/highschool
$ cd tom richard
$ pwd
/mystuff/myproject/richard/hobbies/sports/highschool
我也喜欢Kornshell print
命令以及Kornshell中的变量在循环中不会消失的方式(因为BASH使它们成为子进程)。
当然,BASH具有Kornshell中缺少的功能。一个例子是设置你的提示。在Bash中,我设置了我的提示:
PS1="\u@\h:\w\n\$ "
\u
是用户ID \h
是短主机名\w
是与$HOME
\n
是换行符\$
为$
;如果您的ID为root,则<{1}}为#
。Kornshell的等价物是:
PS1 = $(print -n“logname
@ hostname
:”;如果[[“$ {PWD#$ HOME}”!=“$ PWD”]]则;打印-n “〜$ {PWD#$ HOME}”;否则;打印-n“$ PWD”; fi;打印“\ n $”)
正如我所说,它们大多相当于。我可以使用其中任何一个,但Kornshell有这个特殊功能而BASH没有。
您可以选择编写一个能够为您执行此操作的函数,或者为cd
命令创建别名。
答案 5 :(得分:0)
某些shell(例如Zsh和ksh)提供cd
内置的特殊形式:
cd [ -qsLP ] old new
The second form of cd substitutes the string new for the string old in the
name of the current directory, and tries to change to this new directory.
因此,如果您使用zsh
或ksh
,则此命令应该执行此操作:
cd /mystuff/myproject/tom /mystuff/myproject/richard
无论您目前身处/mystuff/myproject/tom
的哪个子目录。