3

我有多个具有相同子目录和文件结构的目录(例如汤姆理查德哈里)。如果我正在处理一个目录中的文件,是否有一种快速或简单的方法可以 cd 到另一个目录中的等效路径?

例子

pwd=/mystuff/myproject/tom/hobbies/sports/highschool

cd /mystuff/myproject/richard/hobbies/sports/highschool

我希望有一些像 cd pwd 这样的快捷方式,但是在一个命令中更改 tom > richard。

4

6 回答 6

11

以下应该有效:

cd ${PWD/tom/richard}
于 2013-06-13T16:03:09.197 回答
2

这会起作用:

cd $(pwd | perl -pi -e 's/tom/richard/g;')

于 2013-06-13T16:07:52.493 回答
1

如果您知道您所在的目录(例如存储在$dirname变量中):

function dirswitch() {
    newdir="$1"    
    cd $(pwd | sed -e "s#/$dirname/#/$newdir/#")
}

这应该处理 bash 中的工作。因此,如果您在dirname=tom并且想要切换到harry

dirswitch harry

...会成功的。

于 2013-06-13T16:04:18.340 回答
1

您可以为此使用 bash 的历史扩展。

^tom^richard- 这将重新运行上一个命令,替换richardtom.

Bash 历史扩展

于 2013-06-13T16:04:58.210 回答
1

这一切都取决于你的外壳......

大多数人使用 BASH——它是标准的 Linux shell,但 Kornshell 与 BASH 非常相似,并且具有您正在寻找的功能:

$ cd /mystuff/myproject/tom/hobbies/sports/highschool
$ cd tom richard
$ pwd
/mystuff/myproject/richard/hobbies/sports/highschool

我也喜欢 Kornshellprint命令以及 Kornshell 中的变量不会在循环中消失的方式(因为 BASH 使它们成为子进程)。

当然,BASH 具有 Kornshell 中缺少的功能。一个例子是设置你的提示。在 Bash 中,我将提示设置为:

PS1="\u@\h:\w\n\$ "
  • \u是用户 ID
  • \h是短主机名
  • \w是相关的工作目录$HOME
  • \n是换行符
  • \$$如果您的 ID 不是 root 并且您的 ID 是 root,则为a #

Kornshell 等价物是:

PS1=$(print -n " logname@ hostname:";if [[ "${PWD#$HOME}" != "$PWD" ]] then; print -n "~${PWD#$HOME}"; else;打印 -n "$PWD";fi;print "\n$")

正如我所说,它们大多是等价的。我可以使用其中任何一个,但 Kornshell 有这个特殊的功能,而 BASH 没有。

您的替代方法是编写一个为您执行此操作的函数,或者为该cd命令创建一个别名。

于 2013-06-13T16:06:29.720 回答
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.

所以如果你使用zshor ksh,那么这个命令应该这样做:

cd /mystuff/myproject/tom /mystuff/myproject/richard

无论/mystuff/myproject/tom您当前碰巧在哪个子目录中。

于 2013-06-13T16:06:46.720 回答