参数替换 - 删除模式后面的字符串部分

发布于 2024-12-21 21:38:33 字数 474 浏览 0 评论 0原文

假设我有一个如下所示的路径:

/A/B/C/DIRECTORY/D/E/F

现在,我想要使用参数替换实现的目标是剪切 DIRECTORY 之后的路径部分,无论 DIRECTORY 位于路径中的哪个位置(A、B、C)等仅代表随机目录名称)。

替换后:

/A/B/C/DIRECTORY

这是我到目前为止所尝试过的:

#!/bin/bash

if [[ $# < 1 ]]
then
    echo "Usage: $0 DIRECTORY"
fi

CURRENT_DIRECTORY=$(pwd)
DIRECTORY=$1

cd ${CURRENT_DIRECTORY%!(DIRECTORY)/*}

显然,这不起作用。我可以使用 awk 或 sed 来实现这一点,但我很感兴趣是否可以仅使用参数替换。

Let's say I have a path which looks like the following:

/A/B/C/DIRECTORY/D/E/F

Now, what I want to achieve using parameter substitution, is cutting of the part of the path after DIRECTORY, no matter where in the path the DIRECTORY is positioned (A, B, C, etc. just stand for random directory names).

After substitution:

/A/B/C/DIRECTORY

This is what I've tried so far:

#!/bin/bash

if [[ $# < 1 ]]
then
    echo "Usage: $0 DIRECTORY"
fi

CURRENT_DIRECTORY=$(pwd)
DIRECTORY=$1

cd ${CURRENT_DIRECTORY%!(DIRECTORY)/*}

Obviously, this doesn't work. I could implement this using awk or sed but I'm interested if it is possible using only parameter substitution.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

泪冰清 2024-12-28 21:38:33

也许这可以帮助 -

[jaypal:~/Temp] D="A/B/C/DIRECTORY/D/E/F"

[jaypal:~/Temp] echo $D
A/B/C/DIRECTORY/D/E/F

[jaypal:~/Temp] c=${D%/*/*/*}

[jaypal:~/Temp] echo $c
A/B/C/DIRECTORY

May be this can help -

[jaypal:~/Temp] D="A/B/C/DIRECTORY/D/E/F"

[jaypal:~/Temp] echo $D
A/B/C/DIRECTORY/D/E/F

[jaypal:~/Temp] c=${D%/*/*/*}

[jaypal:~/Temp] echo $c
A/B/C/DIRECTORY
∞梦里开花 2024-12-28 21:38:33
[ghoti@pc ~]$ D="/A/B/C/foo/D/E"
[ghoti@pc ~]$ echo "${D/foo*/}"
/A/B/C/

当然,这并不完美:

[ghoti@pc ~]$ D="/A/B/C/foobar/D/foo/E"
[ghoti@pc ~]$ echo "${D/foo*/}"
/A/B/C/

阅读 bash 手册页并搜索“模式替换”。

[ghoti@pc ~]$ D="/A/B/C/foo/D/E"
[ghoti@pc ~]$ echo "${D/foo*/}"
/A/B/C/

of course, this isn't perfect:

[ghoti@pc ~]$ D="/A/B/C/foobar/D/foo/E"
[ghoti@pc ~]$ echo "${D/foo*/}"
/A/B/C/

Read the bash man page and search for "Pattern substitution".

む无字情书 2024-12-28 21:38:33

尝试下一个解决方案:

cd ${CURRENT_DIRECTORY/${DIRECTORY}*/""}

编辑:

更准确的答案是在删除最后一部分后附加您的目录:

cd ${CURRENT_DIRECTORY/${DIRECTORY}*/""}$DIRECTORY

Try next solution:

cd ${CURRENT_DIRECTORY/${DIRECTORY}*/""}

EDIT:

More accurate answer would be appending your directory after removing last part:

cd ${CURRENT_DIRECTORY/${DIRECTORY}*/""}$DIRECTORY
蓝眸 2024-12-28 21:38:33

感谢 Birei,我找到了这个(不完美但足够好的解决方案:

#/bin/bash

if [[ $# < 1 ]]
then
  echo "Usage: $0 BASENAME"
fi

echo ${PWD/%$1*/$1}

示例:

$ PWD=/home/ltorvalds/workspace
$ ./up.sh ltorvalds
/home/ltorvalds    

Thanks to Birei, I came to this (not perfect but good enough solution:

#/bin/bash

if [[ $# < 1 ]]
then
  echo "Usage: $0 BASENAME"
fi

echo ${PWD/%$1*/$1}

Example:

$ PWD=/home/ltorvalds/workspace
$ ./up.sh ltorvalds
/home/ltorvalds    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文